home *** CD-ROM | disk | FTP | other *** search
/ Amiga Plus Special 25 / AMIGAplus Sonderheft 25 (2000)(Falke)(DE)(Track 1 of 4)[!].iso / Updates / PowerPC / bzip2-0.1pl2 / bzip2.c < prev    next >
C/C++ Source or Header  |  1998-08-03  |  116KB  |  4,014 lines

  1.  
  2. /*-----------------------------------------------------------*/
  3. /*--- A block-sorting, lossless compressor        bzip2.c ---*/
  4. /*-----------------------------------------------------------*/
  5.  
  6. /*--
  7.   This program is bzip2, a lossless, block-sorting data compressor,
  8.   version 0.1pl2, dated 29-Aug-1997.
  9.  
  10.   Copyright (C) 1996, 1997 by Julian Seward.
  11.      Guildford, Surrey, UK
  12.      email: jseward@acm.org
  13.  
  14.   This program is free software; you can redistribute it and/or modify
  15.   it under the terms of the GNU General Public License as published by
  16.   the Free Software Foundation; either version 2 of the License, or
  17.   (at your option) any later version.
  18.  
  19.   This program is distributed in the hope that it will be useful,
  20.   but WITHOUT ANY WARRANTY; without even the implied warranty of
  21.   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  22.   GNU General Public License for more details.
  23.  
  24.   You should have received a copy of the GNU General Public License
  25.   along with this program; if not, write to the Free Software
  26.   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  27.  
  28.   The GNU General Public License is contained in the file LICENSE.
  29.  
  30.   This program is based on (at least) the work of:
  31.      Mike Burrows
  32.      David Wheeler
  33.      Peter Fenwick
  34.      Alistair Moffat
  35.      Radford Neal
  36.      Ian H. Witten
  37.      Robert Sedgewick
  38.      Jon L. Bentley
  39.  
  40.   For more information on these sources, see the file ALGORITHMS.
  41. --*/
  42.  
  43. /*----------------------------------------------------*/
  44. /*--- IMPORTANT                                    ---*/
  45. /*----------------------------------------------------*/
  46.  
  47. /*--
  48.    WARNING:
  49.       This program (attempts to) compress data by performing several
  50.       non-trivial transformations on it.  Unless you are 100% familiar
  51.       with *all* the algorithms contained herein, and with the
  52.       consequences of modifying them, you should NOT meddle with the
  53.       compression or decompression machinery.  Incorrect changes can
  54.       and very likely *will* lead to disasterous loss of data.
  55.  
  56.    DISCLAIMER:
  57.       I TAKE NO RESPONSIBILITY FOR ANY LOSS OF DATA ARISING FROM THE
  58.       USE OF THIS PROGRAM, HOWSOEVER CAUSED.
  59.  
  60.       Every compression of a file implies an assumption that the
  61.       compressed file can be decompressed to reproduce the original.
  62.       Great efforts in design, coding and testing have been made to
  63.       ensure that this program works correctly.  However, the
  64.       complexity of the algorithms, and, in particular, the presence
  65.       of various special cases in the code which occur with very low
  66.       but non-zero probability make it impossible to rule out the
  67.       possibility of bugs remaining in the program.  DO NOT COMPRESS
  68.       ANY DATA WITH THIS PROGRAM UNLESS YOU ARE PREPARED TO ACCEPT THE
  69.       POSSIBILITY, HOWEVER SMALL, THAT THE DATA WILL NOT BE RECOVERABLE.
  70.  
  71.       That is not to say this program is inherently unreliable.
  72.       Indeed, I very much hope the opposite is true.  bzip2 has been
  73.       carefully constructed and extensively tested.
  74.  
  75.    PATENTS:
  76.       To the best of my knowledge, bzip2 does not use any patented
  77.       algorithms.  However, I do not have the resources available to
  78.       carry out a full patent search.  Therefore I cannot give any
  79.       guarantee of the above statement.
  80. --*/
  81.  
  82.  
  83.  
  84. /*----------------------------------------------------*/
  85. /*--- and now for something much more pleasant :-) ---*/
  86. /*----------------------------------------------------*/
  87.  
  88. /*---------------------------------------------*/
  89. /*--
  90.   Place a 1 beside your platform, and 0 elsewhere.
  91. --*/
  92.  
  93. /*--
  94.   Generic 32-bit Unix.
  95.   Also works on 64-bit Unix boxes.
  96. --*/
  97. #define BZ_UNIX      1
  98. #define BZ_AMIGA     1
  99. /*--
  100.   Win32, as seen by Jacob Navia's excellent
  101.   port of (Chris Fraser & David Hanson)'s excellent
  102.   lcc compiler.
  103. --*/
  104. #define BZ_LCCWIN32  0
  105.  
  106.  
  107.  
  108. /*---------------------------------------------*/
  109. /*--
  110.   Some stuff for all platforms.
  111. --*/
  112.  
  113. #include <stdio.h>
  114. #include <stdlib.h>
  115. #if DEBUG
  116.   #include <assert.h>
  117. #endif
  118. #include <string.h>
  119. #include <signal.h>
  120. #include <math.h>
  121.  
  122. #define ERROR_IF_EOF(i)       { if ((i) == EOF)  ioError(); }
  123. #define ERROR_IF_NOT_ZERO(i)  { if ((i) != 0)    ioError(); }
  124. #define ERROR_IF_MINUS_ONE(i) { if ((i) == (-1)) ioError(); }
  125.  
  126.  
  127. /*---------------------------------------------*/
  128. /*--
  129.    Platform-specific stuff.
  130. --*/
  131.  
  132. #if BZ_UNIX
  133.    #include <sys/types.h>
  134.    #include <utime.h>
  135.    #include <unistd.h>
  136.    #include <malloc.h>
  137.    #include <sys/stat.h>
  138.  
  139.    #define Int32   int
  140.    #define UInt32  unsigned int
  141.    #define Char    char
  142.    #define UChar   unsigned char
  143.    #define Int16   short
  144.    #define UInt16  unsigned short
  145.  
  146.    #define PATH_SEP    '/'
  147.    #define MY_LSTAT    lstat
  148.    #define MY_S_IFREG  S_ISREG
  149.    #define MY_STAT     stat
  150.  
  151.    #define APPEND_FILESPEC(root, name) \
  152.       root=snocString((root), (name))
  153.  
  154.    #define SET_BINARY_MODE(fd) /**/
  155.  
  156.    /*--
  157.       You should try very hard to persuade your C compiler
  158.       to inline the bits marked INLINE.  Otherwise bzip2 will
  159.       run rather slowly.  gcc version 2.x is recommended.
  160.    --*/
  161.    #ifdef __GNUC__
  162.       #define INLINE   inline
  163.       #define NORETURN __attribute__ ((noreturn))
  164.    #else
  165.       #define INLINE   /**/
  166.       #define NORETURN /**/
  167.    #endif
  168. #endif
  169.  
  170.  
  171.  
  172. #if BZ_LCCWIN32
  173.    #include <io.h>
  174.    #include <fcntl.h>
  175.    #include <sys\stat.h>
  176.  
  177.    #define Int32   int
  178.    #define UInt32  unsigned int
  179.    #define Int16   short
  180.    #define UInt16  unsigned short
  181.    #define Char    char
  182.    #define UChar   unsigned char
  183.  
  184.    #define INLINE         /**/
  185.    #define NORETURN       /**/
  186.    #define PATH_SEP       '\\'
  187.    #define MY_LSTAT       _stat
  188.    #define MY_STAT        _stat
  189.    #define MY_S_IFREG(x)  ((x) & _S_IFREG)
  190.  
  191.    #if 0
  192.    /*-- lcc-win32 seems to expand wildcards itself --*/
  193.    #define APPEND_FILESPEC(root, spec)                \
  194.       do {                                            \
  195.          if ((spec)[0] == '-') {                      \
  196.             root = snocString((root), (spec));        \
  197.          } else {                                     \
  198.             struct _finddata_t c_file;                \
  199.             long hFile;                               \
  200.             hFile = _findfirst((spec), &c_file);      \
  201.             if ( hFile == -1L ) {                     \
  202.                root = snocString ((root), (spec));    \
  203.             } else {                                  \
  204.                int anInt = 0;                         \
  205.                while ( anInt == 0 ) {                 \
  206.                   root = snocString((root),           \
  207.                             &c_file.name[0]);         \
  208.                   anInt = _findnext(hFile, &c_file);  \
  209.                }                                      \
  210.             }                                         \
  211.          }                                            \
  212.       } while ( 0 )
  213.    #else
  214.    #define APPEND_FILESPEC(root, name)                \
  215.       root = snocString ((root), (name))
  216.    #endif
  217.  
  218.    #define SET_BINARY_MODE(fd)                        \
  219.       do {                                            \
  220.          int retVal = setmode ( fileno ( fd ),        \
  221.                                O_BINARY );            \
  222.          ERROR_IF_MINUS_ONE ( retVal );               \
  223.       } while ( 0 )
  224.  
  225. #endif
  226.  
  227.  
  228. /*---------------------------------------------*/
  229. /*--
  230.   Some more stuff for all platforms :-)
  231. --*/
  232.  
  233. #define Bool   unsigned char
  234. #define True   1
  235. #define False  0
  236.  
  237. /*--
  238.   IntNative is your platform's `native' int size.
  239.   Only here to avoid probs with 64-bit platforms.
  240. --*/
  241. #define IntNative int
  242.  
  243.  
  244. /*--
  245.    change to 1, or compile with -DDEBUG=1 to debug
  246. --*/
  247. #ifndef DEBUG
  248. #define DEBUG 0
  249. #endif
  250.  
  251.  
  252. /*---------------------------------------------------*/
  253. /*---                                             ---*/
  254. /*---------------------------------------------------*/
  255.  
  256. /*--
  257.    Implementation notes, July 1997
  258.    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  259.  
  260.    Memory allocation
  261.    ~~~~~~~~~~~~~~~~~
  262.    All large data structures are allocated on the C heap,
  263.    for better or for worse.  That includes the various
  264.    arrays of pointers, striped words, bytes, frequency
  265.    tables and buffers for compression and decompression.
  266.  
  267.    bzip2 can operate at various block-sizes, ranging from
  268.    100k to 900k in 100k steps, and it allocates only as
  269.    much as it needs to.  When compressing, we know from the
  270.    command-line options what the block-size is going to be,
  271.    so all allocation can be done at start-up; if that
  272.    succeeds, there can be no further allocation problems.
  273.  
  274.    Decompression is more complicated.  Each compressed file
  275.    contains, in its header, a byte indicating the block
  276.    size used for compression.  This means bzip2 potentially
  277.    needs to reallocate memory for each file it deals with,
  278.    which in turn opens the possibility for a memory allocation
  279.    failure part way through a run of files, by encountering
  280.    a file requiring a much larger block size than all the
  281.    ones preceding it.
  282.  
  283.    The policy is to simply give up if a memory allocation
  284.    failure occurs.  During decompression, it would be
  285.    possible to move on to subsequent files in the hope that
  286.    some might ask for a smaller block size, but the
  287.    complications for doing this seem more trouble than they
  288.    are worth.
  289.  
  290.  
  291.    Compressed file formats
  292.    ~~~~~~~~~~~~~~~~~~~~~~~
  293.    [This is now entirely different from both 0.21, and from
  294.     any previous Huffman-coded variant of bzip.
  295.     See the associated file bzip2.txt for details.]
  296.  
  297.  
  298.    Error conditions
  299.    ~~~~~~~~~~~~~~~~
  300.    Dealing with error conditions is the least satisfactory
  301.    aspect of bzip2.  The policy is to try and leave the
  302.    filesystem in a consistent state, then quit, even if it
  303.    means not processing some of the files mentioned in the
  304.    command line.  `A consistent state' means that a file
  305.    exists either in its compressed or uncompressed form,
  306.    but not both.  This boils down to the rule `delete the
  307.    output file if an error condition occurs, leaving the
  308.    input intact'.  Input files are only deleted when we can
  309.    be pretty sure the output file has been written and
  310.    closed successfully.
  311.  
  312.    Errors are a dog because there's so many things to
  313.    deal with.  The following can happen mid-file, and
  314.    require cleaning up.
  315.  
  316.      internal `panics' -- indicating a bug
  317.      corrupted or inconsistent compressed file
  318.      can't allocate enough memory to decompress this file
  319.      I/O error reading/writing/opening/closing
  320.      signal catches -- Control-C, SIGTERM, SIGHUP.
  321.  
  322.    Other conditions, primarily pertaining to file names,
  323.    can be checked in-between files, which makes dealing
  324.    with them easier.
  325. --*/
  326.  
  327.  
  328.  
  329. /*---------------------------------------------------*/
  330. /*--- Misc (file handling) data decls             ---*/
  331. /*---------------------------------------------------*/
  332.  
  333. UInt32  bytesIn, bytesOut;
  334. Int32   verbosity;
  335. Bool    keepInputFiles, smallMode, testFailsExist;
  336. UInt32  globalCrc;
  337. Int32   numFileNames, numFilesProcessed;
  338.  
  339.  
  340. /*-- source modes; F==file, I==stdin, O==stdout --*/
  341. #define SM_I2O           1
  342. #define SM_F2O           2
  343. #define SM_F2F           3
  344.  
  345. /*-- operation modes --*/
  346. #define OM_Z             1
  347. #define OM_UNZ           2
  348. #define OM_TEST          3
  349.  
  350. Int32   opMode;
  351. Int32   srcMode;
  352.  
  353.  
  354. Int32   longestFileName;
  355. Char    inName[1024];
  356. Char    outName[1024];
  357. Char    *progName;
  358. Char    progNameReally[1024];
  359. FILE    *outputHandleJustInCase;
  360.  
  361. void    panic                 ( Char* )          NORETURN;
  362. void    ioError               ( void )           NORETURN;
  363. void    compressOutOfMemory   ( Int32, Int32 )   NORETURN;
  364. void    uncompressOutOfMemory ( Int32, Int32 )   NORETURN;
  365. void    blockOverrun          ( void )           NORETURN;
  366. void    badBlockHeader        ( void )           NORETURN;
  367. void    badBGLengths          ( void )           NORETURN;
  368. void    crcError              ( UInt32, UInt32 ) NORETURN;
  369. void    bitStreamEOF          ( void )           NORETURN;
  370. void    cleanUpAndFail        ( Int32 )          NORETURN;
  371. void    compressedStreamEOF   ( void )           NORETURN;
  372.  
  373. void*   myMalloc ( Int32 );
  374.  
  375.  
  376.  
  377. /*---------------------------------------------------*/
  378. /*--- Data decls for the front end                ---*/
  379. /*---------------------------------------------------*/
  380.  
  381. /*--
  382.    The overshoot bytes allow us to avoid most of
  383.    the cost of pointer renormalisation during
  384.    comparison of rotations in sorting.
  385.    The figure of 20 is derived as follows:
  386.       qSort3 allows an overshoot of up to 10.
  387.       It then calls simpleSort, which calls
  388.       fullGtU, also with max overshoot 10.
  389.       fullGtU does up to 10 comparisons without
  390.       renormalising, giving 10+10 == 20.
  391. --*/
  392. #define NUM_OVERSHOOT_BYTES 20
  393.  
  394. /*--
  395.   These are the main data structures for
  396.   the Burrows-Wheeler transform.
  397. --*/
  398.  
  399. /*--
  400.   Pointers to compression and decompression
  401.   structures.  Set by
  402.      allocateCompressStructures   and
  403.      setDecompressStructureSizes
  404.  
  405.   The structures are always set to be suitable
  406.   for a block of size 100000 * blockSize100k.
  407. --*/
  408. UChar    *block;    /*-- compress   --*/
  409. UInt16   *quadrant; /*-- compress   --*/
  410. Int32    *zptr;     /*-- compress   --*/ 
  411. UInt16   *szptr;    /*-- overlays zptr ---*/
  412. Int32    *ftab;     /*-- compress   --*/
  413.  
  414. UInt16   *ll16;     /*-- small decompress --*/
  415. UChar    *ll4;      /*-- small decompress --*/
  416.  
  417. Int32    *tt;       /*-- fast decompress  --*/
  418. UChar    *ll8;      /*-- fast decompress  --*/
  419.  
  420.  
  421. /*--
  422.   freq table collected to save a pass over the data
  423.   during decompression.
  424. --*/
  425. Int32   unzftab[256];
  426.  
  427.  
  428. /*--
  429.    index of the last char in the block, so
  430.    the block size == last + 1.
  431. --*/
  432. Int32  last;
  433.  
  434.  
  435. /*--
  436.   index in zptr[] of original string after sorting.
  437. --*/
  438. Int32  origPtr;
  439.  
  440.  
  441. /*--
  442.   always: in the range 0 .. 9.
  443.   The current block size is 100000 * this number.
  444. --*/
  445. Int32  blockSize100k;
  446.  
  447.  
  448. /*--
  449.   Used when sorting.  If too many long comparisons
  450.   happen, we stop sorting, randomise the block 
  451.   slightly, and try again.
  452. --*/
  453.  
  454. Int32  workFactor;
  455. Int32  workDone;
  456. Int32  workLimit;
  457. Bool   blockRandomised;
  458. Bool   firstAttempt;
  459. Int32  nBlocksRandomised;
  460.  
  461.  
  462.  
  463. /*---------------------------------------------------*/
  464. /*--- Data decls for the back end                 ---*/
  465. /*---------------------------------------------------*/
  466.  
  467. #define MAX_ALPHA_SIZE 258
  468. #define MAX_CODE_LEN    23
  469.  
  470. #define RUNA 0
  471. #define RUNB 1
  472.  
  473. #define N_GROUPS 6
  474. #define G_SIZE   50
  475. #define N_ITERS  4
  476.  
  477. #define MAX_SELECTORS (2 + (900000 / G_SIZE))
  478.  
  479. Bool  inUse[256];
  480. Int32 nInUse;
  481.  
  482. UChar seqToUnseq[256];
  483. UChar unseqToSeq[256];
  484.  
  485. UChar selector   [MAX_SELECTORS];
  486. UChar selectorMtf[MAX_SELECTORS];
  487.  
  488. Int32 nMTF;
  489.  
  490. Int32 mtfFreq[MAX_ALPHA_SIZE];
  491.  
  492. UChar len  [N_GROUPS][MAX_ALPHA_SIZE];
  493.  
  494. /*-- decompress only --*/
  495. Int32 limit  [N_GROUPS][MAX_ALPHA_SIZE];
  496. Int32 base   [N_GROUPS][MAX_ALPHA_SIZE];
  497. Int32 perm   [N_GROUPS][MAX_ALPHA_SIZE];
  498. Int32 minLens[N_GROUPS];
  499.  
  500. /*-- compress only --*/
  501. Int32  code [N_GROUPS][MAX_ALPHA_SIZE];
  502. Int32  rfreq[N_GROUPS][MAX_ALPHA_SIZE];
  503.  
  504.  
  505. /*---------------------------------------------------*/
  506. /*--- 32-bit CRC grunge                           ---*/
  507. /*---------------------------------------------------*/
  508.  
  509. /*--
  510.   I think this is an implementation of the AUTODIN-II,
  511.   Ethernet & FDDI 32-bit CRC standard.  Vaguely derived
  512.   from code by Rob Warnock, in Section 51 of the
  513.   comp.compression FAQ.
  514. --*/
  515.  
  516. UInt32 crc32Table[256] = {
  517.  
  518.    /*-- Ugly, innit? --*/
  519.  
  520.    0x00000000UL, 0x04c11db7UL, 0x09823b6eUL, 0x0d4326d9UL,
  521.    0x130476dcUL, 0x17c56b6bUL, 0x1a864db2UL, 0x1e475005UL,
  522.    0x2608edb8UL, 0x22c9f00fUL, 0x2f8ad6d6UL, 0x2b4bcb61UL,
  523.    0x350c9b64UL, 0x31cd86d3UL, 0x3c8ea00aUL, 0x384fbdbdUL,
  524.    0x4c11db70UL, 0x48d0c6c7UL, 0x4593e01eUL, 0x4152fda9UL,
  525.    0x5f15adacUL, 0x5bd4b01bUL, 0x569796c2UL, 0x52568b75UL,
  526.    0x6a1936c8UL, 0x6ed82b7fUL, 0x639b0da6UL, 0x675a1011UL,
  527.    0x791d4014UL, 0x7ddc5da3UL, 0x709f7b7aUL, 0x745e66cdUL,
  528.    0x9823b6e0UL, 0x9ce2ab57UL, 0x91a18d8eUL, 0x95609039UL,
  529.    0x8b27c03cUL, 0x8fe6dd8bUL, 0x82a5fb52UL, 0x8664e6e5UL,
  530.    0xbe2b5b58UL, 0xbaea46efUL, 0xb7a96036UL, 0xb3687d81UL,
  531.    0xad2f2d84UL, 0xa9ee3033UL, 0xa4ad16eaUL, 0xa06c0b5dUL,
  532.    0xd4326d90UL, 0xd0f37027UL, 0xddb056feUL, 0xd9714b49UL,
  533.    0xc7361b4cUL, 0xc3f706fbUL, 0xceb42022UL, 0xca753d95UL,
  534.    0xf23a8028UL, 0xf6fb9d9fUL, 0xfbb8bb46UL, 0xff79a6f1UL,
  535.    0xe13ef6f4UL, 0xe5ffeb43UL, 0xe8bccd9aUL, 0xec7dd02dUL,
  536.    0x34867077UL, 0x30476dc0UL, 0x3d044b19UL, 0x39c556aeUL,
  537.    0x278206abUL, 0x23431b1cUL, 0x2e003dc5UL, 0x2ac12072UL,
  538.    0x128e9dcfUL, 0x164f8078UL, 0x1b0ca6a1UL, 0x1fcdbb16UL,
  539.    0x018aeb13UL, 0x054bf6a4UL, 0x0808d07dUL, 0x0cc9cdcaUL,
  540.    0x7897ab07UL, 0x7c56b6b0UL, 0x71159069UL, 0x75d48ddeUL,
  541.    0x6b93dddbUL, 0x6f52c06cUL, 0x6211e6b5UL, 0x66d0fb02UL,
  542.    0x5e9f46bfUL, 0x5a5e5b08UL, 0x571d7dd1UL, 0x53dc6066UL,
  543.    0x4d9b3063UL, 0x495a2dd4UL, 0x44190b0dUL, 0x40d816baUL,
  544.    0xaca5c697UL, 0xa864db20UL, 0xa527fdf9UL, 0xa1e6e04eUL,
  545.    0xbfa1b04bUL, 0xbb60adfcUL, 0xb6238b25UL, 0xb2e29692UL,
  546.    0x8aad2b2fUL, 0x8e6c3698UL, 0x832f1041UL, 0x87ee0df6UL,
  547.    0x99a95df3UL, 0x9d684044UL, 0x902b669dUL, 0x94ea7b2aUL,
  548.    0xe0b41de7UL, 0xe4750050UL, 0xe9362689UL, 0xedf73b3eUL,
  549.    0xf3b06b3bUL, 0xf771768cUL, 0xfa325055UL, 0xfef34de2UL,
  550.    0xc6bcf05fUL, 0xc27dede8UL, 0xcf3ecb31UL, 0xcbffd686UL,
  551.    0xd5b88683UL, 0xd1799b34UL, 0xdc3abdedUL, 0xd8fba05aUL,
  552.    0x690ce0eeUL, 0x6dcdfd59UL, 0x608edb80UL, 0x644fc637UL,
  553.    0x7a089632UL, 0x7ec98b85UL, 0x738aad5cUL, 0x774bb0ebUL,
  554.    0x4f040d56UL, 0x4bc510e1UL, 0x46863638UL, 0x42472b8fUL,
  555.    0x5c007b8aUL, 0x58c1663dUL, 0x558240e4UL, 0x51435d53UL,
  556.    0x251d3b9eUL, 0x21dc2629UL, 0x2c9f00f0UL, 0x285e1d47UL,
  557.    0x36194d42UL, 0x32d850f5UL, 0x3f9b762cUL, 0x3b5a6b9bUL,
  558.    0x0315d626UL, 0x07d4cb91UL, 0x0a97ed48UL, 0x0e56f0ffUL,
  559.    0x1011a0faUL, 0x14d0bd4dUL, 0x19939b94UL, 0x1d528623UL,
  560.    0xf12f560eUL, 0xf5ee4bb9UL, 0xf8ad6d60UL, 0xfc6c70d7UL,
  561.    0xe22b20d2UL, 0xe6ea3d65UL, 0xeba91bbcUL, 0xef68060bUL,
  562.    0xd727bbb6UL, 0xd3e6a601UL, 0xdea580d8UL, 0xda649d6fUL,
  563.    0xc423cd6aUL, 0xc0e2d0ddUL, 0xcda1f604UL, 0xc960ebb3UL,
  564.    0xbd3e8d7eUL, 0xb9ff90c9UL, 0xb4bcb610UL, 0xb07daba7UL,
  565.    0xae3afba2UL, 0xaafbe615UL, 0xa7b8c0ccUL, 0xa379dd7bUL,
  566.    0x9b3660c6UL, 0x9ff77d71UL, 0x92b45ba8UL, 0x9675461fUL,
  567.    0x8832161aUL, 0x8cf30badUL, 0x81b02d74UL, 0x857130c3UL,
  568.    0x5d8a9099UL, 0x594b8d2eUL, 0x5408abf7UL, 0x50c9b640UL,
  569.    0x4e8ee645UL, 0x4a4ffbf2UL, 0x470cdd2bUL, 0x43cdc09cUL,
  570.    0x7b827d21UL, 0x7f436096UL, 0x7200464fUL, 0x76c15bf8UL,
  571.    0x68860bfdUL, 0x6c47164aUL, 0x61043093UL, 0x65c52d24UL,
  572.    0x119b4be9UL, 0x155a565eUL, 0x18197087UL, 0x1cd86d30UL,
  573.    0x029f3d35UL, 0x065e2082UL, 0x0b1d065bUL, 0x0fdc1becUL,
  574.    0x3793a651UL, 0x3352bbe6UL, 0x3e119d3fUL, 0x3ad08088UL,
  575.    0x2497d08dUL, 0x2056cd3aUL, 0x2d15ebe3UL, 0x29d4f654UL,
  576.    0xc5a92679UL, 0xc1683bceUL, 0xcc2b1d17UL, 0xc8ea00a0UL,
  577.    0xd6ad50a5UL, 0xd26c4d12UL, 0xdf2f6bcbUL, 0xdbee767cUL,
  578.    0xe3a1cbc1UL, 0xe760d676UL, 0xea23f0afUL, 0xeee2ed18UL,
  579.    0xf0a5bd1dUL, 0xf464a0aaUL, 0xf9278673UL, 0xfde69bc4UL,
  580.    0x89b8fd09UL, 0x8d79e0beUL, 0x803ac667UL, 0x84fbdbd0UL,
  581.    0x9abc8bd5UL, 0x9e7d9662UL, 0x933eb0bbUL, 0x97ffad0cUL,
  582.    0xafb010b1UL, 0xab710d06UL, 0xa6322bdfUL, 0xa2f33668UL,
  583.    0xbcb4666dUL, 0xb8757bdaUL, 0xb5365d03UL, 0xb1f740b4UL
  584. };
  585.  
  586.  
  587. /*---------------------------------------------*/
  588. void initialiseCRC ( void )
  589. {
  590.    globalCrc = 0xffffffffUL;
  591. }
  592.  
  593.  
  594. /*---------------------------------------------*/
  595. UInt32 getFinalCRC ( void )
  596. {
  597.    return ~globalCrc;
  598. }
  599.  
  600.  
  601. /*---------------------------------------------*/
  602. UInt32 getGlobalCRC ( void )
  603. {
  604.    return globalCrc;
  605. }
  606.  
  607.  
  608. /*---------------------------------------------*/
  609. void setGlobalCRC ( UInt32 newCrc )
  610. {
  611.    globalCrc = newCrc;
  612. }
  613.  
  614.  
  615. /*---------------------------------------------*/
  616. #define UPDATE_CRC(crcVar,cha)              \
  617. {                                           \
  618.    crcVar = (crcVar << 8) ^                 \
  619.             crc32Table[(crcVar >> 24) ^     \
  620.                        ((UChar)cha)];       \
  621. }
  622.  
  623.  
  624. /*---------------------------------------------------*/
  625. /*--- Bit stream I/O                              ---*/
  626. /*---------------------------------------------------*/
  627.  
  628.  
  629. UInt32 bsBuff;
  630. Int32  bsLive;
  631. FILE*  bsStream;
  632. Bool   bsWriting;
  633.  
  634.  
  635. /*---------------------------------------------*/
  636. void bsSetStream ( FILE* f, Bool wr )
  637. {
  638.    if (bsStream != NULL) panic ( "bsSetStream" );
  639.    bsStream = f;
  640.    bsLive = 0;
  641.    bsBuff = 0;
  642.    bytesOut = 0;
  643.    bytesIn = 0;
  644.    bsWriting = wr;
  645. }
  646.  
  647.  
  648. /*---------------------------------------------*/
  649. void bsFinishedWithStream ( void )
  650. {
  651.    if (bsWriting)
  652.       while (bsLive > 0) {
  653.          fputc ( (UChar)(bsBuff >> 24), bsStream );
  654.          bsBuff <<= 8;
  655.          bsLive -= 8;
  656.          bytesOut++;
  657.       }
  658.    bsStream = NULL;
  659. }
  660.  
  661.  
  662. /*---------------------------------------------*/
  663. #define bsNEEDR(nz)                           \
  664. {                                             \
  665.    while (bsLive < nz) {                      \
  666.       Int32 zzi = fgetc ( bsStream );         \
  667.       if (zzi == EOF) compressedStreamEOF();  \
  668.       bsBuff = (bsBuff << 8) | (zzi & 0xffL); \
  669.       bsLive += 8;                            \
  670.    }                                          \
  671. }
  672.  
  673.  
  674. /*---------------------------------------------*/
  675. #define bsNEEDW(nz)                           \
  676. {                                             \
  677.    while (bsLive >= 8) {                      \
  678.       fputc ( (UChar)(bsBuff >> 24),          \
  679.                bsStream );                    \
  680.       bsBuff <<= 8;                           \
  681.       bsLive -= 8;                            \
  682.       bytesOut++;                             \
  683.    }                                          \
  684. }
  685.  
  686.  
  687. /*---------------------------------------------*/
  688. #define bsR1(vz)                              \
  689. {                                             \
  690.    bsNEEDR(1);                                \
  691.    vz = (bsBuff >> (bsLive-1)) & 1;           \
  692.    bsLive--;                                  \
  693. }
  694.  
  695.  
  696. /*---------------------------------------------*/
  697. INLINE UInt32 bsR ( Int32 n )
  698. {
  699.    UInt32 v;
  700.    bsNEEDR ( n );
  701.    v = (bsBuff >> (bsLive-n)) & ((1 << n)-1);
  702.    bsLive -= n;
  703.    return v;
  704. }
  705.  
  706.  
  707. /*---------------------------------------------*/
  708. INLINE void bsW ( Int32 n, UInt32 v )
  709. {
  710.    bsNEEDW ( n );
  711.    bsBuff |= (v << (32 - bsLive - n));
  712.    bsLive += n;
  713. }
  714.  
  715.  
  716. /*---------------------------------------------*/
  717. UChar bsGetUChar ( void )
  718. {
  719.    return (UChar)bsR(8);
  720. }
  721.  
  722.  
  723. /*---------------------------------------------*/
  724. void bsPutUChar ( UChar c )
  725. {
  726.    bsW(8, (UInt32)c );
  727. }
  728.  
  729.  
  730. /*---------------------------------------------*/
  731. Int32 bsGetUInt32 ( void )
  732. {
  733.    UInt32 u;
  734.    u = 0;
  735.    u = (u << 8) | bsR(8);
  736.    u = (u << 8) | bsR(8);
  737.    u = (u << 8) | bsR(8);
  738.    u = (u << 8) | bsR(8);
  739.    return u;
  740. }
  741.  
  742.  
  743. /*---------------------------------------------*/
  744. UInt32 bsGetIntVS ( UInt32 numBits )
  745. {
  746.    return (UInt32)bsR(numBits);
  747. }
  748.  
  749.  
  750. /*---------------------------------------------*/
  751. UInt32 bsGetInt32 ( void )
  752. {
  753.    return (Int32)bsGetUInt32();
  754. }
  755.  
  756.  
  757. /*---------------------------------------------*/
  758. void bsPutUInt32 ( UInt32 u )
  759. {
  760.    bsW ( 8, (u >> 24) & 0xffL );
  761.    bsW ( 8, (u >> 16) & 0xffL );
  762.    bsW ( 8, (u >>  8) & 0xffL );
  763.    bsW ( 8,  u        & 0xffL );
  764. }
  765.  
  766.  
  767. /*---------------------------------------------*/
  768. void bsPutInt32 ( Int32 c )
  769. {
  770.    bsPutUInt32 ( (UInt32)c );
  771. }
  772.  
  773.  
  774. /*---------------------------------------------*/
  775. void bsPutIntVS ( Int32 numBits, UInt32 c )
  776. {
  777.    bsW ( numBits, c );
  778. }
  779.  
  780.  
  781. /*---------------------------------------------------*/
  782. /*--- Huffman coding low-level stuff              ---*/
  783. /*---------------------------------------------------*/
  784.  
  785. #define WEIGHTOF(zz0)  ((zz0) & 0xffffff00)
  786. #define DEPTHOF(zz1)   ((zz1) & 0x000000ff)
  787. #define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3))
  788.  
  789. #define ADDWEIGHTS(zw1,zw2)                           \
  790.    (WEIGHTOF(zw1)+WEIGHTOF(zw2)) |                    \
  791.    (1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2)))
  792.  
  793. #define UPHEAP(z)                                     \
  794. {                                                     \
  795.    Int32 zz, tmp;                                     \
  796.    zz = z; tmp = heap[zz];                            \
  797.    while (weight[tmp] < weight[heap[zz >> 1]]) {      \
  798.       heap[zz] = heap[zz >> 1];                       \
  799.       zz >>= 1;                                       \
  800.    }                                                  \
  801.    heap[zz] = tmp;                                    \
  802. }
  803.  
  804. #define DOWNHEAP(z)                                   \
  805. {                                                     \
  806.    Int32 zz, yy, tmp;                                 \
  807.    zz = z; tmp = heap[zz];                            \
  808.    while (True) {                                     \
  809.       yy = zz << 1;                                   \
  810.       if (yy > nHeap) break;                          \
  811.       if (yy < nHeap &&                               \
  812.           weight[heap[yy+1]] < weight[heap[yy]])      \
  813.          yy++;                                        \
  814.       if (weight[tmp] < weight[heap[yy]]) break;      \
  815.       heap[zz] = heap[yy];                            \
  816.       zz = yy;                                        \
  817.    }                                                  \
  818.    heap[zz] = tmp;                                    \
  819. }
  820.  
  821.  
  822. /*---------------------------------------------*/
  823. void hbMakeCodeLengths ( UChar *len, 
  824.                          Int32 *freq,
  825.                          Int32 alphaSize,
  826.                          Int32 maxLen )
  827. {
  828.    /*--
  829.       Nodes and heap entries run from 1.  Entry 0
  830.       for both the heap and nodes is a sentinel.
  831.    --*/
  832.    Int32 nNodes, nHeap, n1, n2, i, j, k;
  833.    Bool  tooLong;
  834.  
  835.    Int32 heap   [ MAX_ALPHA_SIZE + 2 ];
  836.    Int32 weight [ MAX_ALPHA_SIZE * 2 ];
  837.    Int32 parent [ MAX_ALPHA_SIZE * 2 ]; 
  838.  
  839.    for (i = 0; i < alphaSize; i++)
  840.       weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
  841.  
  842.    while (True) {
  843.  
  844.       nNodes = alphaSize;
  845.       nHeap = 0;
  846.  
  847.       heap[0] = 0;
  848.       weight[0] = 0;
  849.       parent[0] = -2;
  850.  
  851.       for (i = 1; i <= alphaSize; i++) {
  852.          parent[i] = -1;
  853.          nHeap++;
  854.          heap[nHeap] = i;
  855.          UPHEAP(nHeap);
  856.       }
  857.       if (!(nHeap < (MAX_ALPHA_SIZE+2))) 
  858.          panic ( "hbMakeCodeLengths(1)" );
  859.    
  860.       while (nHeap > 1) {
  861.          n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
  862.          n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
  863.          nNodes++;
  864.          parent[n1] = parent[n2] = nNodes;
  865.          weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]);
  866.          parent[nNodes] = -1;
  867.          nHeap++;
  868.          heap[nHeap] = nNodes;
  869.          UPHEAP(nHeap);
  870.       }
  871.       if (!(nNodes < (MAX_ALPHA_SIZE * 2)))
  872.          panic ( "hbMakeCodeLengths(2)" );
  873.  
  874.       tooLong = False;
  875.       for (i = 1; i <= alphaSize; i++) {
  876.          j = 0;
  877.          k = i;
  878.          while (parent[k] >= 0) { k = parent[k]; j++; }
  879.          len[i-1] = j;
  880.          if (j > maxLen) tooLong = True;
  881.       }
  882.       
  883.       if (! tooLong) break;
  884.  
  885.       for (i = 1; i < alphaSize; i++) {
  886.          j = weight[i] >> 8;
  887.          j = 1 + (j / 2);
  888.          weight[i] = j << 8;
  889.       }
  890.    }
  891. }
  892.  
  893.  
  894. /*---------------------------------------------*/
  895. void hbAssignCodes ( Int32 *code,
  896.                      UChar *length,
  897.                      Int32 minLen,
  898.                      Int32 maxLen,
  899.                      Int32 alphaSize )
  900. {
  901.    Int32 n, vec, i;
  902.  
  903.    vec = 0;
  904.    for (n = minLen; n <= maxLen; n++) {
  905.       for (i = 0; i < alphaSize; i++)
  906.          if (length[i] == n) { code[i] = vec; vec++; };
  907.       vec <<= 1;
  908.    }
  909. }
  910.  
  911.  
  912. /*---------------------------------------------*/
  913. void hbCreateDecodeTables ( Int32 *limit,
  914.                             Int32 *base,
  915.                             Int32 *perm,
  916.                             UChar *length,
  917.                             Int32 minLen,
  918.                             Int32 maxLen,
  919.                             Int32 alphaSize )
  920. {
  921.    Int32 pp, i, j, vec;
  922.  
  923.    pp = 0;
  924.    for (i = minLen; i <= maxLen; i++)
  925.       for (j = 0; j < alphaSize; j++)
  926.          if (length[j] == i) { perm[pp] = j; pp++; };
  927.  
  928.    for (i = 0; i < MAX_CODE_LEN; i++) base[i] = 0;
  929.    for (i = 0; i < alphaSize; i++) base[length[i]+1]++;
  930.  
  931.    for (i = 1; i < MAX_CODE_LEN; i++) base[i] += base[i-1];
  932.  
  933.    for (i = 0; i < MAX_CODE_LEN; i++) limit[i] = 0;
  934.    vec = 0;
  935.  
  936.    for (i = minLen; i <= maxLen; i++) {
  937.       vec += (base[i+1] - base[i]);
  938.       limit[i] = vec-1;
  939.       vec <<= 1;
  940.    }
  941.    for (i = minLen + 1; i <= maxLen; i++)
  942.       base[i] = ((limit[i-1] + 1) << 1) - base[i];
  943. }
  944.  
  945.  
  946.  
  947. /*---------------------------------------------------*/
  948. /*--- Undoing the reversible transformation       ---*/
  949. /*---------------------------------------------------*/
  950.  
  951. /*---------------------------------------------*/
  952. #define SET_LL4(i,n)                                          \
  953.    { if (((i) & 0x1) == 0)                                    \
  954.         ll4[(i) >> 1] = (ll4[(i) >> 1] & 0xf0) | (n); else    \
  955.         ll4[(i) >> 1] = (ll4[(i) >> 1] & 0x0f) | ((n) << 4);  \
  956.    }
  957.  
  958. #define GET_LL4(i)                             \
  959.     (((UInt32)(ll4[(i) >> 1])) >> (((i) << 2) & 0x4) & 0xF)
  960.  
  961. #define SET_LL(i,n)                       \
  962.    { ll16[i] = (UInt16)(n & 0x0000ffff);  \
  963.      SET_LL4(i, n >> 16);                 \
  964.    }
  965.  
  966. #define GET_LL(i) \
  967.    (((UInt32)ll16[i]) | (GET_LL4(i) << 16))
  968.  
  969.  
  970. /*---------------------------------------------*/
  971. /*--
  972.   Manage memory for compression/decompression.
  973.   When compressing, a single block size applies to
  974.   all files processed, and that's set when the
  975.   program starts.  But when decompressing, each file
  976.   processed could have been compressed with a
  977.   different block size, so we may have to free
  978.   and reallocate on a per-file basis.
  979.  
  980.   A call with argument of zero means
  981.   `free up everything.'  And a value of zero for
  982.   blockSize100k means no memory is currently allocated.
  983. --*/
  984.  
  985.  
  986. /*---------------------------------------------*/
  987. void allocateCompressStructures ( void )
  988. {
  989.    Int32 n  = 100000 * blockSize100k;
  990.    block    = malloc ( (n + 1 + NUM_OVERSHOOT_BYTES) * sizeof(UChar) );
  991.    quadrant = malloc ( (n     + NUM_OVERSHOOT_BYTES) * sizeof(Int16) );
  992.    zptr     = malloc ( n                             * sizeof(Int32) );
  993.    ftab     = malloc ( 65537                         * sizeof(Int32) );
  994.  
  995.    if (block == NULL || quadrant == NULL ||
  996.        zptr == NULL  || ftab == NULL) {
  997.       Int32 totalDraw
  998.          = (n + 1 + NUM_OVERSHOOT_BYTES) * sizeof(UChar) +
  999.            (n     + NUM_OVERSHOOT_BYTES) * sizeof(Int16) +
  1000.            n                             * sizeof(Int32) +
  1001.            65537                         * sizeof(Int32);
  1002.  
  1003.       compressOutOfMemory ( totalDraw, n );
  1004.    }
  1005.  
  1006.    /*--
  1007.       Since we want valid indexes for block of
  1008.       -1 to n + NUM_OVERSHOOT_BYTES - 1
  1009.       inclusive.
  1010.    --*/
  1011.    block++;
  1012.  
  1013.    /*--
  1014.       The back end needs a place to store the MTF values
  1015.       whilst it calculates the coding tables.  We could
  1016.       put them in the zptr array.  However, these values
  1017.       will fit in a short, so we overlay szptr at the 
  1018.       start of zptr, in the hope of reducing the number
  1019.       of cache misses induced by the multiple traversals
  1020.       of the MTF values when calculating coding tables.
  1021.       Seems to improve compression speed by about 1%.
  1022.    --*/
  1023.    szptr = (UInt16*)zptr;
  1024. }
  1025.  
  1026.  
  1027. /*---------------------------------------------*/
  1028. void setDecompressStructureSizes ( Int32 newSize100k )
  1029. {
  1030.    if (! (0 <= newSize100k   && newSize100k   <= 9 &&
  1031.           0 <= blockSize100k && blockSize100k <= 9))
  1032.       panic ( "setDecompressStructureSizes" );
  1033.  
  1034.    if (newSize100k == blockSize100k) return;
  1035.  
  1036.    blockSize100k = newSize100k;
  1037.  
  1038.    if (ll16  != NULL) free ( ll16  );
  1039.    if (ll4   != NULL) free ( ll4   );
  1040.    if (ll8   != NULL) free ( ll8   );
  1041.    if (tt    != NULL) free ( tt    );
  1042.  
  1043.    if (newSize100k == 0) return;
  1044.  
  1045.    if (smallMode) {
  1046.  
  1047.       Int32 n = 100000 * newSize100k;
  1048.       ll16    = malloc ( n * sizeof(UInt16) );
  1049.       ll4     = malloc ( ((n+1) >> 1) * sizeof(UChar) );
  1050.  
  1051.       if (ll4 == NULL || ll16 == NULL) {
  1052.          Int32 totalDraw
  1053.             = n * sizeof(Int16) + ((n+1) >> 1) * sizeof(UChar);
  1054.          uncompressOutOfMemory ( totalDraw, n );
  1055.       }
  1056.  
  1057.    } else {
  1058.  
  1059.       Int32 n = 100000 * newSize100k;
  1060.       ll8     = malloc ( n * sizeof(UChar) );
  1061.       tt      = malloc ( n * sizeof(Int32) );
  1062.  
  1063.       if (ll8 == NULL || tt == NULL) {
  1064.          Int32 totalDraw
  1065.             = n * sizeof(UChar) + n * sizeof(UInt32);
  1066.          uncompressOutOfMemory ( totalDraw, n );
  1067.       }
  1068.  
  1069.    }
  1070. }
  1071.  
  1072.  
  1073.  
  1074. /*---------------------------------------------------*/
  1075. /*--- The new back end                            ---*/
  1076. /*---------------------------------------------------*/
  1077.  
  1078. /*---------------------------------------------*/
  1079. void makeMaps ( void )
  1080. {
  1081.    Int32 i;
  1082.    nInUse = 0;
  1083.    for (i = 0; i < 256; i++)
  1084.       if (inUse[i]) {
  1085.          seqToUnseq[nInUse] = i;
  1086.          unseqToSeq[i] = nInUse;
  1087.          nInUse++;
  1088.       }
  1089. }
  1090.  
  1091.  
  1092. /*---------------------------------------------*/
  1093. void generateMTFValues ( void )
  1094. {
  1095.    UChar  yy[256];
  1096.    Int32  i, j;
  1097.    UChar  tmp;
  1098.    UChar  tmp2;
  1099.    Int32  zPend;
  1100.    Int32  wr;
  1101.    Int32  EOB;
  1102.  
  1103.    makeMaps();
  1104.    EOB = nInUse+1;
  1105.  
  1106.    for (i = 0; i <= EOB; i++) mtfFreq[i] = 0;
  1107.  
  1108.    wr = 0;
  1109.    zPend = 0;
  1110.    for (i = 0; i < nInUse; i++) yy[i] = (UChar) i;
  1111.    
  1112.  
  1113.    for (i = 0; i <= last; i++) {
  1114.       UChar ll_i;
  1115.  
  1116.       #if DEBUG
  1117.          assert (wr <= i);
  1118.       #endif
  1119.  
  1120.       ll_i = unseqToSeq[block[zptr[i] - 1]];
  1121.       #if DEBUG
  1122.          assert (ll_i < nInUse);
  1123.       #endif
  1124.  
  1125.       j = 0;
  1126.       tmp = yy[j];
  1127.       while ( ll_i != tmp ) {
  1128.          j++;
  1129.          tmp2 = tmp;
  1130.          tmp = yy[j];
  1131.          yy[j] = tmp2;
  1132.       };
  1133.       yy[0] = tmp;
  1134.  
  1135.       if (j == 0) {
  1136.          zPend++;
  1137.       } else {
  1138.          if (zPend > 0) {
  1139.             zPend--;
  1140.             while (True) {
  1141.                switch (zPend % 2) {
  1142.                   case 0: szptr[wr] = RUNA; wr++; mtfFreq[RUNA]++; break;
  1143.                   case 1: szptr[wr] = RUNB; wr++; mtfFreq[RUNB]++; break;
  1144.                };
  1145.                if (zPend < 2) break;
  1146.                zPend = (zPend - 2) / 2;
  1147.             };
  1148.             zPend = 0;
  1149.          }
  1150.          szptr[wr] = j+1; wr++; mtfFreq[j+1]++;
  1151.       }
  1152.    }
  1153.  
  1154.    if (zPend > 0) {
  1155.       zPend--;
  1156.       while (True) {
  1157.          switch (zPend % 2) {
  1158.             case 0:  szptr[wr] = RUNA; wr++; mtfFreq[RUNA]++; break;
  1159.             case 1:  szptr[wr] = RUNB; wr++; mtfFreq[RUNB]++; break;
  1160.          };
  1161.          if (zPend < 2) break;
  1162.          zPend = (zPend - 2) / 2;
  1163.       };
  1164.    }
  1165.  
  1166.    szptr[wr] = EOB; wr++; mtfFreq[EOB]++;
  1167.  
  1168.    nMTF = wr;
  1169. }
  1170.  
  1171.  
  1172. /*---------------------------------------------*/
  1173. #define LESSER_ICOST  0
  1174. #define GREATER_ICOST 15
  1175.  
  1176. void sendMTFValues ( void )
  1177. {
  1178.    Int32 v, t, i, j, gs, ge, totc, bt, bc, iter;
  1179.    Int32 nSelectors, alphaSize, minLen, maxLen, selCtr;
  1180.    Int32 nGroups, nBytes;
  1181.  
  1182.    /*--
  1183.    UChar  len [N_GROUPS][MAX_ALPHA_SIZE];
  1184.    is a global since the decoder also needs it.
  1185.  
  1186.    Int32  code[N_GROUPS][MAX_ALPHA_SIZE];
  1187.    Int32  rfreq[N_GROUPS][MAX_ALPHA_SIZE];
  1188.    are also globals only used in this proc.
  1189.    Made global to keep stack frame size small.
  1190.    --*/
  1191.  
  1192.  
  1193.    UInt16 cost[N_GROUPS];
  1194.    Int32  fave[N_GROUPS];
  1195.  
  1196.    if (verbosity >= 3)
  1197.       fprintf ( stderr, 
  1198.                 "      %d in block, %d after MTF & 1-2 coding, %d+2 syms in use\n", 
  1199.                 last+1, nMTF, nInUse );
  1200.  
  1201.    alphaSize = nInUse+2;
  1202.    for (t = 0; t < N_GROUPS; t++)
  1203.       for (v = 0; v < alphaSize; v++)
  1204.          len[t][v] = GREATER_ICOST;
  1205.  
  1206.    /*--- Decide how many coding tables to use ---*/
  1207.    if (nMTF <= 0) panic ( "sendMTFValues(0)" );
  1208.    if (nMTF < 200) nGroups = 2; else
  1209.    if (nMTF < 800) nGroups = 4; else
  1210.                    nGroups = 6;
  1211.  
  1212.    /*--- Generate an initial set of coding tables ---*/
  1213.    { 
  1214.       Int32 nPart, remF, tFreq, aFreq;
  1215.  
  1216.       nPart = nGroups;
  1217.       remF  = nMTF;
  1218.       gs = 0;
  1219.       while (nPart > 0) {
  1220.          tFreq = remF / nPart;
  1221.          ge = gs-1;
  1222.          aFreq = 0;
  1223.          while (aFreq < tFreq && ge < alphaSize-1) {
  1224.             ge++;
  1225.             aFreq += mtfFreq[ge];
  1226.          }
  1227.  
  1228.          if (ge > gs 
  1229.              && nPart != nGroups && nPart != 1 
  1230.              && ((nGroups-nPart) % 2 == 1)) {
  1231.             aFreq -= mtfFreq[ge];
  1232.             ge--;
  1233.          }
  1234.  
  1235.          if (verbosity >= 3)
  1236.             fprintf ( stderr, 
  1237.                       "      initial group %d, [%d .. %d], has %d syms (%4.1f%%)\n",
  1238.                               nPart, gs, ge, aFreq, 
  1239.                               (100.0 * (float)aFreq) / (float)nMTF );
  1240.  
  1241.          for (v = 0; v < alphaSize; v++)
  1242.             if (v >= gs && v <= ge) 
  1243.                len[nPart-1][v] = LESSER_ICOST; else
  1244.                len[nPart-1][v] = GREATER_ICOST;
  1245.  
  1246.          nPart--;
  1247.          gs = ge+1;
  1248.          remF -= aFreq;
  1249.       }
  1250.    }
  1251.  
  1252.    /*--- 
  1253.       Iterate up to N_ITERS times to improve the tables.
  1254.    ---*/
  1255.    for (iter = 0; iter < N_ITERS; iter++) {
  1256.  
  1257.       for (t = 0; t < nGroups; t++) fave[t] = 0;
  1258.  
  1259.       for (t = 0; t < nGroups; t++)
  1260.          for (v = 0; v < alphaSize; v++)
  1261.             rfreq[t][v] = 0;
  1262.  
  1263.       nSelectors = 0;
  1264.       totc = 0;
  1265.       gs = 0;
  1266.       while (True) {
  1267.  
  1268.          /*--- Set group start & end marks. --*/
  1269.          if (gs >= nMTF) break;
  1270.          ge = gs + G_SIZE - 1; 
  1271.          if (ge >= nMTF) ge = nMTF-1;
  1272.  
  1273.          /*-- 
  1274.             Calculate the cost of this group as coded
  1275.             by each of the coding tables.
  1276.          --*/
  1277.          for (t = 0; t < nGroups; t++) cost[t] = 0;
  1278.  
  1279.          if (nGroups == 6) {
  1280.             register UInt16 cost0, cost1, cost2, cost3, cost4, cost5;
  1281.             cost0 = cost1 = cost2 = cost3 = cost4 = cost5 = 0;
  1282.             for (i = gs; i <= ge; i++) { 
  1283.                UInt16 icv = szptr[i];
  1284.                cost0 += len[0][icv];
  1285.                cost1 += len[1][icv];
  1286.                cost2 += len[2][icv];
  1287.                cost3 += len[3][icv];
  1288.                cost4 += len[4][icv];
  1289.                cost5 += len[5][icv];
  1290.             }
  1291.             cost[0] = cost0; cost[1] = cost1; cost[2] = cost2;
  1292.             cost[3] = cost3; cost[4] = cost4; cost[5] = cost5;
  1293.          } else {
  1294.             for (i = gs; i <= ge; i++) { 
  1295.                UInt16 icv = szptr[i];
  1296.                for (t = 0; t < nGroups; t++) cost[t] += len[t][icv];
  1297.             }
  1298.          }
  1299.  
  1300.          /*-- 
  1301.             Find the coding table which is best for this group,
  1302.             and record its identity in the selector table.
  1303.          --*/
  1304.          bc = 999999999; bt = -1;
  1305.          for (t = 0; t < nGroups; t++)
  1306.             if (cost[t] < bc) { bc = cost[t]; bt = t; };
  1307.          totc += bc;
  1308.          fave[bt]++;
  1309.          selector[nSelectors] = bt;
  1310.          nSelectors++;
  1311.  
  1312.          /*-- 
  1313.             Increment the symbol frequencies for the selected table.
  1314.           --*/
  1315.          for (i = gs; i <= ge; i++)
  1316.             rfreq[bt][ szptr[i] ]++;
  1317.  
  1318.          gs = ge+1;
  1319.       }
  1320.       if (verbosity >= 3) {
  1321.          fprintf ( stderr, 
  1322.                    "      pass %d: size is %d, grp uses are ", 
  1323.                    iter+1, totc/8 );
  1324.          for (t = 0; t < nGroups; t++)
  1325.             fprintf ( stderr, "%d ", fave[t] );
  1326.          fprintf ( stderr, "\n" );
  1327.       }
  1328.  
  1329.       /*--
  1330.         Recompute the tables based on the accumulated frequencies.
  1331.       --*/
  1332.       for (t = 0; t < nGroups; t++)
  1333.          hbMakeCodeLengths ( &len[t][0], &rfreq[t][0], alphaSize, 20 );
  1334.    }
  1335.  
  1336.  
  1337.    if (!(nGroups < 8)) panic ( "sendMTFValues(1)" );
  1338.    if (!(nSelectors < 32768 &&
  1339.          nSelectors <= (2 + (900000 / G_SIZE))))
  1340.                        panic ( "sendMTFValues(2)" );
  1341.  
  1342.  
  1343.    /*--- Compute MTF values for the selectors. ---*/
  1344.    {
  1345.       UChar pos[N_GROUPS], ll_i, tmp2, tmp;
  1346.       for (i = 0; i < nGroups; i++) pos[i] = i;
  1347.       for (i = 0; i < nSelectors; i++) {
  1348.          ll_i = selector[i];
  1349.          j = 0;
  1350.          tmp = pos[j];
  1351.          while ( ll_i != tmp ) {
  1352.             j++;
  1353.             tmp2 = tmp;
  1354.             tmp = pos[j];
  1355.             pos[j] = tmp2;
  1356.          };
  1357.          pos[0] = tmp;
  1358.          selectorMtf[i] = j;
  1359.       }
  1360.    };
  1361.  
  1362.    /*--- Assign actual codes for the tables. --*/
  1363.    for (t = 0; t < nGroups; t++) {
  1364.       minLen = 32;
  1365.       maxLen = 0;
  1366.       for (i = 0; i < alphaSize; i++) {
  1367.          if (len[t][i] > maxLen) maxLen = len[t][i];
  1368.          if (len[t][i] < minLen) minLen = len[t][i];
  1369.       }
  1370.       if (maxLen > 20) panic ( "sendMTFValues(3)" );
  1371.       if (minLen < 1)  panic ( "sendMTFValues(4)" );
  1372.       hbAssignCodes ( &code[t][0], &len[t][0], 
  1373.                       minLen, maxLen, alphaSize );
  1374.    }
  1375.  
  1376.    /*--- Transmit the mapping table. ---*/
  1377.    { 
  1378.       Bool inUse16[16];
  1379.       for (i = 0; i < 16; i++) {
  1380.           inUse16[i] = False;
  1381.           for (j = 0; j < 16; j++)
  1382.              if (inUse[i * 16 + j]) inUse16[i] = True;
  1383.       }
  1384.      
  1385.       nBytes = bytesOut;
  1386.       for (i = 0; i < 16; i++)
  1387.          if (inUse16[i]) bsW(1,1); else bsW(1,0);
  1388.  
  1389.       for (i = 0; i < 16; i++)
  1390.          if (inUse16[i])
  1391.             for (j = 0; j < 16; j++)
  1392.                if (inUse[i * 16 + j]) bsW(1,1); else bsW(1,0);
  1393.  
  1394.       if (verbosity >= 3) 
  1395.          fprintf ( stderr, "      bytes: mapping %d, ", bytesOut-nBytes );
  1396.    }
  1397.  
  1398.    /*--- Now the selectors. ---*/
  1399.    nBytes = bytesOut;
  1400.    bsW ( 3, nGroups );
  1401.    bsW ( 15, nSelectors );
  1402.    for (i = 0; i < nSelectors; i++) { 
  1403.       for (j = 0; j < selectorMtf[i]; j++) bsW(1,1);
  1404.       bsW(1,0);
  1405.    }
  1406.    if (verbosity >= 3)
  1407.       fprintf ( stderr, "selectors %d, ", bytesOut-nBytes );
  1408.  
  1409.    /*--- Now the coding tables. ---*/
  1410.    nBytes = bytesOut;
  1411.  
  1412.    for (t = 0; t < nGroups; t++) {
  1413.       Int32 curr = len[t][0];
  1414.       bsW ( 5, curr );
  1415.       for (i = 0; i < alphaSize; i++) {
  1416.          while (curr < len[t][i]) { bsW(2,2); curr++; /* 10 */ };
  1417.          while (curr > len[t][i]) { bsW(2,3); curr--; /* 11 */ };
  1418.          bsW ( 1, 0 );
  1419.       }
  1420.    }
  1421.  
  1422.    if (verbosity >= 3)
  1423.       fprintf ( stderr, "code lengths %d, ", bytesOut-nBytes );
  1424.  
  1425.    /*--- And finally, the block data proper ---*/
  1426.    nBytes = bytesOut;
  1427.    selCtr = 0;
  1428.    gs = 0;
  1429.    while (True) {
  1430.       if (gs >= nMTF) break;
  1431.       ge = gs + G_SIZE - 1; 
  1432.       if (ge >= nMTF) ge = nMTF-1;
  1433.       for (i = gs; i <= ge; i++) { 
  1434.          #if DEBUG
  1435.             assert (selector[selCtr] < nGroups);
  1436.          #endif
  1437.          bsW ( len  [selector[selCtr]] [szptr[i]],
  1438.                code [selector[selCtr]] [szptr[i]] );
  1439.       }
  1440.  
  1441.       gs = ge+1;
  1442.       selCtr++;
  1443.    }
  1444.    if (!(selCtr == nSelectors)) panic ( "sendMTFValues(5)" );
  1445.  
  1446.    if (verbosity >= 3)
  1447.       fprintf ( stderr, "codes %d\n", bytesOut-nBytes );
  1448. }
  1449.  
  1450.  
  1451. /*---------------------------------------------*/
  1452. void moveToFrontCodeAndSend ( void )
  1453. {
  1454.    bsPutIntVS ( 24, origPtr );
  1455.    generateMTFValues();
  1456.    sendMTFValues();
  1457. }
  1458.  
  1459.  
  1460. /*---------------------------------------------*/
  1461. void recvDecodingTables ( void )
  1462. {
  1463.    Int32 i, j, t, nGroups, nSelectors, alphaSize;
  1464.    Int32 minLen, maxLen;
  1465.    Bool inUse16[16];
  1466.  
  1467.    /*--- Receive the mapping table ---*/
  1468.    for (i = 0; i < 16; i++)
  1469.       if (bsR(1) == 1) 
  1470.          inUse16[i] = True; else 
  1471.          inUse16[i] = False;
  1472.  
  1473.    for (i = 0; i < 256; i++) inUse[i] = False;
  1474.  
  1475.    for (i = 0; i < 16; i++)
  1476.       if (inUse16[i])
  1477.          for (j = 0; j < 16; j++)
  1478.             if (bsR(1) == 1) inUse[i * 16 + j] = True;
  1479.  
  1480.    makeMaps();
  1481.    alphaSize = nInUse+2;
  1482.  
  1483.    /*--- Now the selectors ---*/
  1484.    nGroups = bsR ( 3 );
  1485.    nSelectors = bsR ( 15 );
  1486.    for (i = 0; i < nSelectors; i++) {
  1487.       j = 0;
  1488.       while (bsR(1) == 1) j++;
  1489.       selectorMtf[i] = j;
  1490.    }
  1491.  
  1492.    /*--- Undo the MTF values for the selectors. ---*/
  1493.    {
  1494.       UChar pos[N_GROUPS], tmp, v;
  1495.       for (v = 0; v < nGroups; v++) pos[v] = v;
  1496.    
  1497.       for (i = 0; i < nSelectors; i++) {
  1498.          v = selectorMtf[i];
  1499.          tmp = pos[v];
  1500.          while (v > 0) { pos[v] = pos[v-1]; v--; }
  1501.          pos[0] = tmp;
  1502.          selector[i] = tmp;
  1503.       }
  1504.    }
  1505.  
  1506.    /*--- Now the coding tables ---*/
  1507.    for (t = 0; t < nGroups; t++) {
  1508.       Int32 curr = bsR ( 5 );
  1509.       for (i = 0; i < alphaSize; i++) {
  1510.          while (bsR(1) == 1) {
  1511.             if (bsR(1) == 0) curr++; else curr--;
  1512.          }
  1513.          len[t][i] = curr;
  1514.       }
  1515.    }
  1516.  
  1517.    /*--- Create the Huffman decoding tables ---*/
  1518.    for (t = 0; t < nGroups; t++) {
  1519.       minLen = 32;
  1520.       maxLen = 0;
  1521.       for (i = 0; i < alphaSize; i++) {
  1522.          if (len[t][i] > maxLen) maxLen = len[t][i];
  1523.          if (len[t][i] < minLen) minLen = len[t][i];
  1524.       }
  1525.       hbCreateDecodeTables ( 
  1526.          &limit[t][0], &base[t][0], &perm[t][0], &len[t][0],
  1527.          minLen, maxLen, alphaSize
  1528.       );
  1529.       minLens[t] = minLen;
  1530.    }
  1531. }
  1532.  
  1533.  
  1534. /*---------------------------------------------*/
  1535. #define GET_MTF_VAL(lval)                 \
  1536. {                                         \
  1537.    Int32 zt, zn, zvec, zj;                \
  1538.    if (groupPos == 0) {                   \
  1539.       groupNo++;                          \
  1540.       groupPos = G_SIZE;                  \
  1541.    }                                      \
  1542.    groupPos--;                            \
  1543.    zt = selector[groupNo];                \
  1544.    zn = minLens[zt];                      \
  1545.    zvec = bsR ( zn );                     \
  1546.    while (zvec > limit[zt][zn]) {         \
  1547.       zn++; bsR1(zj);                     \
  1548.       zvec = (zvec << 1) | zj;            \
  1549.    };                                     \
  1550.    lval = perm[zt][zvec - base[zt][zn]];  \
  1551. }
  1552.  
  1553.  
  1554. /*---------------------------------------------*/
  1555. void getAndMoveToFrontDecode ( void )
  1556. {
  1557.    UChar  yy[256];
  1558.    Int32  i, j, nextSym, limitLast;
  1559.    Int32  EOB, groupNo, groupPos;
  1560.  
  1561.    limitLast = 100000 * blockSize100k;
  1562.    origPtr   = bsGetIntVS ( 24 );
  1563.  
  1564.    recvDecodingTables();
  1565.    EOB      = nInUse+1;
  1566.    groupNo  = -1;
  1567.    groupPos = 0;
  1568.  
  1569.    /*--
  1570.       Setting up the unzftab entries here is not strictly
  1571.       necessary, but it does save having to do it later
  1572.       in a separate pass, and so saves a block's worth of
  1573.       cache misses.
  1574.    --*/
  1575.    for (i = 0; i <= 255; i++) unzftab[i] = 0;
  1576.  
  1577.    for (i = 0; i <= 255; i++) yy[i] = (UChar) i;
  1578.  
  1579.    last = -1;
  1580.  
  1581.    GET_MTF_VAL(nextSym);
  1582.  
  1583.    while (True) {
  1584.  
  1585.       if (nextSym == EOB) break;
  1586.  
  1587.       if (nextSym == RUNA || nextSym == RUNB) {
  1588.          UChar ch;
  1589.          Int32 s = -1;
  1590.          Int32 N = 1;
  1591.          do {
  1592.             if (nextSym == RUNA) s = s + (0+1) * N; else
  1593.             if (nextSym == RUNB) s = s + (1+1) * N;
  1594.             N = N * 2;
  1595.             GET_MTF_VAL(nextSym);
  1596.          }
  1597.             while (nextSym == RUNA || nextSym == RUNB);
  1598.  
  1599.          s++;
  1600.          ch = seqToUnseq[yy[0]];
  1601.          unzftab[ch] += s;
  1602.  
  1603.          if (smallMode)
  1604.             while (s > 0) {
  1605.                last++; 
  1606.                ll16[last] = ch;
  1607.                s--;
  1608.             }
  1609.          else
  1610.             while (s > 0) {
  1611.                last++;
  1612.                ll8[last] = ch;
  1613.                s--;
  1614.             };
  1615.  
  1616.          if (last >= limitLast) blockOverrun();
  1617.          continue;
  1618.  
  1619.       } else {
  1620.  
  1621.          UChar tmp;
  1622.          last++; if (last >= limitLast) blockOverrun();
  1623.  
  1624.          tmp = yy[nextSym-1];
  1625.          unzftab[seqToUnseq[tmp]]++;
  1626.          if (smallMode)
  1627.             ll16[last] = seqToUnseq[tmp]; else
  1628.             ll8[last]  = seqToUnseq[tmp];
  1629.  
  1630.          /*--
  1631.             This loop is hammered during decompression,
  1632.             hence the unrolling.
  1633.  
  1634.             for (j = nextSym-1; j > 0; j--) yy[j] = yy[j-1];
  1635.          --*/
  1636.  
  1637.          j = nextSym-1;
  1638.          for (; j > 3; j -= 4) {
  1639.             yy[j]   = yy[j-1];
  1640.             yy[j-1] = yy[j-2];
  1641.             yy[j-2] = yy[j-3];
  1642.             yy[j-3] = yy[j-4];
  1643.          }
  1644.          for (; j > 0; j--) yy[j] = yy[j-1];
  1645.  
  1646.          yy[0] = tmp;
  1647.          GET_MTF_VAL(nextSym);
  1648.          continue;
  1649.       }
  1650.    }
  1651. }
  1652.  
  1653.  
  1654. /*---------------------------------------------------*/
  1655. /*--- Block-sorting machinery                     ---*/
  1656. /*---------------------------------------------------*/
  1657.  
  1658. /*---------------------------------------------*/
  1659. /*--
  1660.   Compare two strings in block.  We assume (see
  1661.   discussion above) that i1 and i2 have a max
  1662.   offset of 10 on entry, and that the first
  1663.   bytes of both block and quadrant have been
  1664.   copied into the "overshoot area", ie
  1665.   into the subscript range
  1666.   [last+1 .. last+NUM_OVERSHOOT_BYTES].
  1667. --*/
  1668. INLINE Bool fullGtU ( Int32 i1, Int32 i2 )
  1669. {
  1670.    Int32 k;
  1671.    UChar c1, c2;
  1672.    UInt16 s1, s2;
  1673.  
  1674.    #if DEBUG
  1675.       /*--
  1676.         shellsort shouldn't ask to compare
  1677.         something with itself.
  1678.       --*/
  1679.       assert (i1 != i2);
  1680.    #endif
  1681.  
  1682.    c1 = block[i1];
  1683.    c2 = block[i2];
  1684.    if (c1 != c2) return (c1 > c2);
  1685.    i1++; i2++;
  1686.  
  1687.    c1 = block[i1];
  1688.    c2 = block[i2];
  1689.    if (c1 != c2) return (c1 > c2);
  1690.    i1++; i2++;
  1691.  
  1692.    c1 = block[i1];
  1693.    c2 = block[i2];
  1694.    if (c1 != c2) return (c1 > c2);
  1695.    i1++; i2++;
  1696.  
  1697.    c1 = block[i1];
  1698.    c2 = block[i2];
  1699.    if (c1 != c2) return (c1 > c2);
  1700.    i1++; i2++;
  1701.  
  1702.    c1 = block[i1];
  1703.    c2 = block[i2];
  1704.    if (c1 != c2) return (c1 > c2);
  1705.    i1++; i2++;
  1706.  
  1707.    c1 = block[i1];
  1708.    c2 = block[i2];
  1709.    if (c1 != c2) return (c1 > c2);
  1710.    i1++; i2++;
  1711.  
  1712.    k = last + 1;
  1713.  
  1714.    do {
  1715.  
  1716.       c1 = block[i1];
  1717.       c2 = block[i2];
  1718.       if (c1 != c2) return (c1 > c2);
  1719.       s1 = quadrant[i1];
  1720.       s2 = quadrant[i2];
  1721.       if (s1 != s2) return (s1 > s2);
  1722.       i1++; i2++;
  1723.  
  1724.       c1 = block[i1];
  1725.       c2 = block[i2];
  1726.       if (c1 != c2) return (c1 > c2);
  1727.       s1 = quadrant[i1];
  1728.       s2 = quadrant[i2];
  1729.       if (s1 != s2) return (s1 > s2);
  1730.       i1++; i2++;
  1731.  
  1732.       c1 = block[i1];
  1733.       c2 = block[i2];
  1734.       if (c1 != c2) return (c1 > c2);
  1735.       s1 = quadrant[i1];
  1736.       s2 = quadrant[i2];
  1737.       if (s1 != s2) return (s1 > s2);
  1738.       i1++; i2++;
  1739.  
  1740.       c1 = block[i1];
  1741.       c2 = block[i2];
  1742.       if (c1 != c2) return (c1 > c2);
  1743.       s1 = quadrant[i1];
  1744.       s2 = quadrant[i2];
  1745.       if (s1 != s2) return (s1 > s2);
  1746.       i1++; i2++;
  1747.  
  1748.       if (i1 > last) { i1 -= last; i1--; };
  1749.       if (i2 > last) { i2 -= last; i2--; };
  1750.  
  1751.       k -= 4;
  1752.       workDone++;
  1753.    }
  1754.       while (k >= 0);
  1755.  
  1756.    return False;
  1757. }
  1758.  
  1759. /*---------------------------------------------*/
  1760. /*--
  1761.    Knuth's increments seem to work better
  1762.    than Incerpi-Sedgewick here.  Possibly
  1763.    because the number of elems to sort is
  1764.    usually small, typically <= 20.
  1765. --*/
  1766. Int32 incs[14] = { 1, 4, 13, 40, 121, 364, 1093, 3280,
  1767.                    9841, 29524, 88573, 265720,
  1768.                    797161, 2391484 };
  1769.  
  1770. void simpleSort ( Int32 lo, Int32 hi, Int32 d )
  1771. {
  1772.    Int32 i, j, h, bigN, hp;
  1773.    Int32 v;
  1774.  
  1775.    bigN = hi - lo + 1;
  1776.    if (bigN < 2) return;
  1777.  
  1778.    hp = 0;
  1779.    while (incs[hp] < bigN) hp++;
  1780.    hp--;
  1781.  
  1782.    for (; hp >= 0; hp--) {
  1783.       h = incs[hp];
  1784.       if (verbosity >= 5) 
  1785.          fprintf ( stderr, "          shell increment %d\n", h );
  1786.  
  1787.       i = lo + h;
  1788.       while (True) {
  1789.  
  1790.          /*-- copy 1 --*/
  1791.          if (i > hi) break;
  1792.          v = zptr[i];
  1793.          j = i;
  1794.          while ( fullGtU ( zptr[j-h]+d, v+d ) ) {
  1795.             zptr[j] = zptr[j-h];
  1796.             j = j - h;
  1797.             if (j <= (lo + h - 1)) break;
  1798.          }
  1799.          zptr[j] = v;
  1800.          i++;
  1801.  
  1802.          /*-- copy 2 --*/
  1803.          if (i > hi) break;
  1804.          v = zptr[i];
  1805.          j = i;
  1806.          while ( fullGtU ( zptr[j-h]+d, v+d ) ) {
  1807.             zptr[j] = zptr[j-h];
  1808.             j = j - h;
  1809.             if (j <= (lo + h - 1)) break;
  1810.          }
  1811.          zptr[j] = v;
  1812.          i++;
  1813.  
  1814.          /*-- copy 3 --*/
  1815.          if (i > hi) break;
  1816.          v = zptr[i];
  1817.          j = i;
  1818.          while ( fullGtU ( zptr[j-h]+d, v+d ) ) {
  1819.             zptr[j] = zptr[j-h];
  1820.             j = j - h;
  1821.             if (j <= (lo + h - 1)) break;
  1822.          }
  1823.          zptr[j] = v;
  1824.          i++;
  1825.  
  1826.          if (workDone > workLimit && firstAttempt) return;
  1827.       }
  1828.    }
  1829. }
  1830.  
  1831.  
  1832. /*---------------------------------------------*/
  1833. /*--
  1834.    The following is an implementation of
  1835.    an elegant 3-way quicksort for strings,
  1836.    described in a paper "Fast Algorithms for
  1837.    Sorting and Searching Strings", by Robert
  1838.    Sedgewick and Jon L. Bentley.
  1839. --*/
  1840.  
  1841. #define swap(lv1, lv2) \
  1842.    { Int32 tmp = lv1; lv1 = lv2; lv2 = tmp; }
  1843.  
  1844. INLINE void vswap ( Int32 p1, Int32 p2, Int32 n )
  1845. {
  1846.    while (n > 0) {
  1847.       swap(zptr[p1], zptr[p2]);
  1848.       p1++; p2++; n--;
  1849.    }
  1850. }
  1851.  
  1852. INLINE UChar med3 ( UChar a, UChar b, UChar c )
  1853. {
  1854.    UChar t;
  1855.    if (a > b) { t = a; a = b; b = t; };
  1856.    if (b > c) { t = b; b = c; c = t; };
  1857.    if (a > b)          b = a;
  1858.    return b;
  1859. }
  1860.  
  1861.  
  1862. #define min(a,b) ((a) < (b)) ? (a) : (b)
  1863.  
  1864. typedef
  1865.    struct { Int32 ll; Int32 hh; Int32 dd; }
  1866.    StackElem;
  1867.  
  1868. #define push(lz,hz,dz) { stack[sp].ll = lz; \
  1869.                          stack[sp].hh = hz; \
  1870.                          stack[sp].dd = dz; \
  1871.                          sp++; }
  1872.  
  1873. #define pop(lz,hz,dz) { sp--;               \
  1874.                         lz = stack[sp].ll;  \
  1875.                         hz = stack[sp].hh;  \
  1876.                         dz = stack[sp].dd; }
  1877.  
  1878. #define SMALL_THRESH 20
  1879. #define DEPTH_THRESH 10
  1880.  
  1881. /*--
  1882.    If you are ever unlucky/improbable enough
  1883.    to get a stack overflow whilst sorting,
  1884.    increase the following constant and try
  1885.    again.  In practice I have never seen the
  1886.    stack go above 27 elems, so the following
  1887.    limit seems very generous.
  1888. --*/
  1889. #define QSORT_STACK_SIZE 1000
  1890.  
  1891.  
  1892. void qSort3 ( Int32 loSt, Int32 hiSt, Int32 dSt )
  1893. {
  1894.    Int32 unLo, unHi, ltLo, gtHi, med, n, m;
  1895.    Int32 sp, lo, hi, d;
  1896.    StackElem stack[QSORT_STACK_SIZE];
  1897.  
  1898.    sp = 0;
  1899.    push ( loSt, hiSt, dSt );
  1900.  
  1901.    while (sp > 0) {
  1902.  
  1903.       if (sp >= QSORT_STACK_SIZE) panic ( "stack overflow in qSort3" );
  1904.  
  1905.       pop ( lo, hi, d );
  1906.  
  1907.       if (hi - lo < SMALL_THRESH || d > DEPTH_THRESH) {
  1908.          simpleSort ( lo, hi, d );
  1909.          if (workDone > workLimit && firstAttempt) return;
  1910.          continue;
  1911.       }
  1912.  
  1913.       med = med3 ( block[zptr[ lo         ]+d],
  1914.                    block[zptr[ hi         ]+d],
  1915.                    block[zptr[ (lo+hi)>>1 ]+d] );
  1916.  
  1917.       unLo = ltLo = lo;
  1918.       unHi = gtHi = hi;
  1919.  
  1920.       while (True) {
  1921.          while (True) {
  1922.             if (unLo > unHi) break;
  1923.             n = ((Int32)block[zptr[unLo]+d]) - med;
  1924.             if (n == 0) { swap(zptr[unLo], zptr[ltLo]); ltLo++; unLo++; continue; };
  1925.             if (n >  0) break;
  1926.             unLo++;
  1927.          }
  1928.          while (True) {
  1929.             if (unLo > unHi) break;
  1930.             n = ((Int32)block[zptr[unHi]+d]) - med;
  1931.             if (n == 0) { swap(zptr[unHi], zptr[gtHi]); gtHi--; unHi--; continue; };
  1932.             if (n <  0) break;
  1933.             unHi--;
  1934.          }
  1935.          if (unLo > unHi) break;
  1936.          swap(zptr[unLo], zptr[unHi]); unLo++; unHi--;
  1937.       }
  1938.       #if DEBUG
  1939.          assert (unHi == unLo-1);
  1940.       #endif
  1941.  
  1942.       if (gtHi < ltLo) {
  1943.          push(lo, hi, d+1 );
  1944.          continue;
  1945.       }
  1946.  
  1947.       n = min(ltLo-lo, unLo-ltLo); vswap(lo, unLo-n, n);
  1948.       m = min(hi-gtHi, gtHi-unHi); vswap(unLo, hi-m+1, m);
  1949.  
  1950.       n = lo + unLo - ltLo - 1;
  1951.       m = hi - (gtHi - unHi) + 1;
  1952.  
  1953.       push ( lo, n, d );
  1954.       push ( n+1, m-1, d+1 );
  1955.       push ( m, hi, d );
  1956.    }
  1957. }
  1958.  
  1959.  
  1960. /*---------------------------------------------*/
  1961.  
  1962. #define BIGFREQ(b) (ftab[((b)+1) << 8] - ftab[(b) << 8])
  1963.  
  1964. #define SETMASK (1 << 21)
  1965. #define CLEARMASK (~(SETMASK))
  1966.  
  1967. void sortIt ( void )
  1968. {
  1969.    Int32 i, j, ss, sb;
  1970.    Int32 runningOrder[256];
  1971.    Int32 copy[256];
  1972.    Bool bigDone[256];
  1973.    UChar c1, c2;
  1974.    Int32 numQSorted;
  1975.  
  1976.    /*--
  1977.       In the various block-sized structures, live data runs
  1978.       from 0 to last+NUM_OVERSHOOT_BYTES inclusive.  First,
  1979.       set up the overshoot area for block.
  1980.    --*/
  1981.  
  1982.    if (verbosity >= 4) fprintf ( stderr, "        sort initialise ...\n" );
  1983.    for (i = 0; i < NUM_OVERSHOOT_BYTES; i++)
  1984.        block[last+i+1] = block[i % (last+1)];
  1985.    for (i = 0; i <= last+NUM_OVERSHOOT_BYTES; i++)
  1986.        quadrant[i] = 0;
  1987.  
  1988.    block[-1] = block[last];
  1989.  
  1990.    if (last < 4000) {
  1991.  
  1992.       /*--
  1993.          Use simpleSort(), since the full sorting mechanism
  1994.          has quite a large constant overhead.
  1995.       --*/
  1996.       if (verbosity >= 4) fprintf ( stderr, "        simpleSort ...\n" );
  1997.       for (i = 0; i <= last; i++) zptr[i] = i;
  1998.       firstAttempt = False;
  1999.       workDone = workLimit = 0;
  2000.       simpleSort ( 0, last, 0 );
  2001.       if (verbosity >= 4) fprintf ( stderr, "        simpleSort done.\n" );
  2002.  
  2003.    } else {
  2004.  
  2005.       numQSorted = 0;
  2006.       for (i = 0; i <= 255; i++) bigDone[i] = False;
  2007.  
  2008.       if (verbosity >= 4) fprintf ( stderr, "        bucket sorting ...\n" );
  2009.  
  2010.       for (i = 0; i <= 65536; i++) ftab[i] = 0;
  2011.  
  2012.       c1 = block[-1];
  2013.       for (i = 0; i <= last; i++) {
  2014.          c2 = block[i];
  2015.          ftab[(c1 << 8) + c2]++;
  2016.          c1 = c2;
  2017.       }
  2018.  
  2019.       for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1];
  2020.  
  2021.       c1 = block[0];
  2022.       for (i = 0; i < last; i++) {
  2023.          c2 = block[i+1];
  2024.          j = (c1 << 8) + c2;
  2025.          c1 = c2;
  2026.          ftab[j]--;
  2027.          zptr[ftab[j]] = i;
  2028.       }
  2029.       j = (block[last] << 8) + block[0];
  2030.       ftab[j]--;
  2031.       zptr[ftab[j]] = last;
  2032.  
  2033.       /*--
  2034.          Now ftab contains the first loc of every small bucket.
  2035.          Calculate the running order, from smallest to largest
  2036.          big bucket.
  2037.       --*/
  2038.  
  2039.       for (i = 0; i <= 255; i++) runningOrder[i] = i;
  2040.  
  2041.       {
  2042.          Int32 vv;
  2043.          Int32 h = 1;
  2044.          do h = 3 * h + 1; while (h <= 256);
  2045.          do {
  2046.             h = h / 3;
  2047.             for (i = h; i <= 255; i++) {
  2048.                vv = runningOrder[i];
  2049.                j = i;
  2050.                while ( BIGFREQ(runningOrder[j-h]) > BIGFREQ(vv) ) {
  2051.                   runningOrder[j] = runningOrder[j-h];
  2052.                   j = j - h;
  2053.                   if (j <= (h - 1)) goto zero;
  2054.                }
  2055.                zero:
  2056.                runningOrder[j] = vv;
  2057.             }
  2058.          } while (h != 1);
  2059.       }
  2060.  
  2061.       /*--
  2062.          The main sorting loop.
  2063.       --*/
  2064.  
  2065.       for (i = 0; i <= 255; i++) {
  2066.  
  2067.          /*--
  2068.             Process big buckets, starting with the least full.
  2069.          --*/
  2070.          ss = runningOrder[i];
  2071.  
  2072.          /*--
  2073.             Complete the big bucket [ss] by quicksorting
  2074.             any unsorted small buckets [ss, j].  Hopefully
  2075.             previous pointer-scanning phases have already
  2076.             completed many of the small buckets [ss, j], so
  2077.             we don't have to sort them at all.
  2078.          --*/
  2079.          for (j = 0; j <= 255; j++) {
  2080.             sb = (ss << 8) + j;
  2081.             if ( ! (ftab[sb] & SETMASK) ) {
  2082.                Int32 lo = ftab[sb]   & CLEARMASK;
  2083.                Int32 hi = (ftab[sb+1] & CLEARMASK) - 1;
  2084.                if (hi > lo) {
  2085.                   if (verbosity >= 4)
  2086.                      fprintf ( stderr,
  2087.                                "        qsort [0x%x, 0x%x]   done %d   this %d\n",
  2088.                                ss, j, numQSorted, hi - lo + 1 );
  2089.                   qSort3 ( lo, hi, 2 );
  2090.                   numQSorted += ( hi - lo + 1 );
  2091.                   if (workDone > workLimit && firstAttempt) return;
  2092.                }
  2093.                ftab[sb] |= SETMASK;
  2094.             }
  2095.          }
  2096.  
  2097.          /*--
  2098.             The ss big bucket is now done.  Record this fact,
  2099.             and update the quadrant descriptors.  Remember to
  2100.             update quadrants in the overshoot area too, if
  2101.             necessary.  The "if (i < 255)" test merely skips
  2102.             this updating for the last bucket processed, since
  2103.             updating for the last bucket is pointless.
  2104.          --*/
  2105.          bigDone[ss] = True;
  2106.  
  2107.          if (i < 255) {
  2108.             Int32 bbStart  = ftab[ss << 8] & CLEARMASK;
  2109.             Int32 bbSize   = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart;
  2110.             Int32 shifts   = 0;
  2111.  
  2112.             while ((bbSize >> shifts) > 65534) shifts++;
  2113.  
  2114.             for (j = 0; j < bbSize; j++) {
  2115.                Int32 a2update     = zptr[bbStart + j];
  2116.                UInt16 qVal        = (UInt16)(j >> shifts);
  2117.                quadrant[a2update] = qVal;
  2118.                if (a2update < NUM_OVERSHOOT_BYTES)
  2119.                   quadrant[a2update + last + 1] = qVal;
  2120.             }
  2121.  
  2122.             if (! ( ((bbSize-1) >> shifts) <= 65535 )) panic ( "sortIt" );
  2123.          }
  2124.  
  2125.          /*--
  2126.             Now scan this big bucket so as to synthesise the
  2127.             sorted order for small buckets [t, ss] for all t != ss.
  2128.          --*/
  2129.          for (j = 0; j <= 255; j++)
  2130.             copy[j] = ftab[(j << 8) + ss] & CLEARMASK;
  2131.  
  2132.          for (j = ftab[ss << 8] & CLEARMASK;
  2133.               j < (ftab[(ss+1) << 8] & CLEARMASK);
  2134.               j++) {
  2135.             c1 = block[zptr[j]-1];
  2136.             if ( ! bigDone[c1] ) {
  2137.                zptr[copy[c1]] = zptr[j] == 0 ? last : zptr[j] - 1;
  2138.                copy[c1] ++;
  2139.             }
  2140.          }
  2141.  
  2142.          for (j = 0; j <= 255; j++) ftab[(j << 8) + ss] |= SETMASK;
  2143.       }
  2144.       if (verbosity >= 4)
  2145.          fprintf ( stderr, "        %d pointers, %d sorted, %d scanned\n",
  2146.                            last+1, numQSorted, (last+1) - numQSorted );
  2147.    }
  2148. }
  2149.  
  2150.  
  2151. /*---------------------------------------------------*/
  2152. /*--- Stuff for randomising repetitive blocks     ---*/
  2153. /*---------------------------------------------------*/
  2154.  
  2155. /*---------------------------------------------*/
  2156. Int32 rNums[512] = { 
  2157.    619, 720, 127, 481, 931, 816, 813, 233, 566, 247, 
  2158.    985, 724, 205, 454, 863, 491, 741, 242, 949, 214, 
  2159.    733, 859, 335, 708, 621, 574, 73, 654, 730, 472, 
  2160.    419, 436, 278, 496, 867, 210, 399, 680, 480, 51, 
  2161.    878, 465, 811, 169, 869, 675, 611, 697, 867, 561, 
  2162.    862, 687, 507, 283, 482, 129, 807, 591, 733, 623, 
  2163.    150, 238, 59, 379, 684, 877, 625, 169, 643, 105, 
  2164.    170, 607, 520, 932, 727, 476, 693, 425, 174, 647, 
  2165.    73, 122, 335, 530, 442, 853, 695, 249, 445, 515, 
  2166.    909, 545, 703, 919, 874, 474, 882, 500, 594, 612, 
  2167.    641, 801, 220, 162, 819, 984, 589, 513, 495, 799, 
  2168.    161, 604, 958, 533, 221, 400, 386, 867, 600, 782, 
  2169.    382, 596, 414, 171, 516, 375, 682, 485, 911, 276, 
  2170.    98, 553, 163, 354, 666, 933, 424, 341, 533, 870, 
  2171.    227, 730, 475, 186, 263, 647, 537, 686, 600, 224, 
  2172.    469, 68, 770, 919, 190, 373, 294, 822, 808, 206, 
  2173.    184, 943, 795, 384, 383, 461, 404, 758, 839, 887, 
  2174.    715, 67, 618, 276, 204, 918, 873, 777, 604, 560, 
  2175.    951, 160, 578, 722, 79, 804, 96, 409, 713, 940, 
  2176.    652, 934, 970, 447, 318, 353, 859, 672, 112, 785, 
  2177.    645, 863, 803, 350, 139, 93, 354, 99, 820, 908, 
  2178.    609, 772, 154, 274, 580, 184, 79, 626, 630, 742, 
  2179.    653, 282, 762, 623, 680, 81, 927, 626, 789, 125, 
  2180.    411, 521, 938, 300, 821, 78, 343, 175, 128, 250, 
  2181.    170, 774, 972, 275, 999, 639, 495, 78, 352, 126, 
  2182.    857, 956, 358, 619, 580, 124, 737, 594, 701, 612, 
  2183.    669, 112, 134, 694, 363, 992, 809, 743, 168, 974, 
  2184.    944, 375, 748, 52, 600, 747, 642, 182, 862, 81, 
  2185.    344, 805, 988, 739, 511, 655, 814, 334, 249, 515, 
  2186.    897, 955, 664, 981, 649, 113, 974, 459, 893, 228, 
  2187.    433, 837, 553, 268, 926, 240, 102, 654, 459, 51, 
  2188.    686, 754, 806, 760, 493, 403, 415, 394, 687, 700, 
  2189.    946, 670, 656, 610, 738, 392, 760, 799, 887, 653, 
  2190.    978, 321, 576, 617, 626, 502, 894, 679, 243, 440, 
  2191.    680, 879, 194, 572, 640, 724, 926, 56, 204, 700, 
  2192.    707, 151, 457, 449, 797, 195, 791, 558, 945, 679, 
  2193.    297, 59, 87, 824, 713, 663, 412, 693, 342, 606, 
  2194.    134, 108, 571, 364, 631, 212, 174, 643, 304, 329, 
  2195.    343, 97, 430, 751, 497, 314, 983, 374, 822, 928, 
  2196.    140, 206, 73, 263, 980, 736, 876, 478, 430, 305, 
  2197.    170, 514, 364, 692, 829, 82, 855, 953, 676, 246, 
  2198.    369, 970, 294, 750, 807, 827, 150, 790, 288, 923, 
  2199.    804, 378, 215, 828, 592, 281, 565, 555, 710, 82, 
  2200.    896, 831, 547, 261, 524, 462, 293, 465, 502, 56, 
  2201.    661, 821, 976, 991, 658, 869, 905, 758, 745, 193, 
  2202.    768, 550, 608, 933, 378, 286, 215, 979, 792, 961, 
  2203.    61, 688, 793, 644, 986, 403, 106, 366, 905, 644, 
  2204.    372, 567, 466, 434, 645, 210, 389, 550, 919, 135, 
  2205.    780, 773, 635, 389, 707, 100, 626, 958, 165, 504, 
  2206.    920, 176, 193, 713, 857, 265, 203, 50, 668, 108, 
  2207.    645, 990, 626, 197, 510, 357, 358, 850, 858, 364, 
  2208.    936, 638
  2209. };
  2210.  
  2211.  
  2212. #define RAND_DECLS                                \
  2213.    Int32 rNToGo = 0;                              \
  2214.    Int32 rTPos  = 0;                              \
  2215.  
  2216. #define RAND_MASK ((rNToGo == 1) ? 1 : 0)
  2217.  
  2218. #define RAND_UPD_MASK                             \
  2219.    if (rNToGo == 0) {                             \
  2220.       rNToGo = rNums[rTPos];                      \
  2221.       rTPos++; if (rTPos == 512) rTPos = 0;       \
  2222.    }                                              \
  2223.    rNToGo--;
  2224.  
  2225.  
  2226.  
  2227. /*---------------------------------------------------*/
  2228. /*--- The Reversible Transformation (tm)          ---*/
  2229. /*---------------------------------------------------*/
  2230.  
  2231. /*---------------------------------------------*/
  2232. void randomiseBlock ( void )
  2233. {
  2234.    Int32 i;
  2235.    RAND_DECLS;
  2236.    for (i = 0; i < 256; i++) inUse[i] = False;
  2237.  
  2238.    for (i = 0; i <= last; i++) {
  2239.       RAND_UPD_MASK;
  2240.       block[i] ^= RAND_MASK;
  2241.       inUse[block[i]] = True;
  2242.    }
  2243. }
  2244.  
  2245.  
  2246. /*---------------------------------------------*/
  2247. void doReversibleTransformation ( void )
  2248. {
  2249.    Int32 i;
  2250.  
  2251.    if (verbosity >= 2) fprintf ( stderr, "\n" );
  2252.  
  2253.    workLimit       = workFactor * last;
  2254.    workDone        = 0;
  2255.    blockRandomised = False;
  2256.    firstAttempt    = True;
  2257.  
  2258.    sortIt ();
  2259.  
  2260.    if (verbosity >= 3)
  2261.       fprintf ( stderr, "      %d work, %d block, ratio %5.2f\n",
  2262.                         workDone, last, (float)workDone / (float)(last) );
  2263.  
  2264.    if (workDone > workLimit && firstAttempt) {
  2265.       if (verbosity >= 2)
  2266.          fprintf ( stderr, "    sorting aborted; randomising block\n" );
  2267.       randomiseBlock ();
  2268.       workLimit = workDone = 0;
  2269.       blockRandomised = True;
  2270.       firstAttempt = False;
  2271.       sortIt();
  2272.       if (verbosity >= 3)
  2273.          fprintf ( stderr, "      %d work, %d block, ratio %f\n",
  2274.                            workDone, last, (float)workDone / (float)(last) );
  2275.    }
  2276.  
  2277.    origPtr = -1;
  2278.    for (i = 0; i <= last; i++)
  2279.        if (zptr[i] == 0)
  2280.           { origPtr = i; break; };
  2281.  
  2282.    if (origPtr == -1) panic ( "doReversibleTransformation" );
  2283. }
  2284.  
  2285.  
  2286. /*---------------------------------------------*/
  2287.  
  2288. INLINE Int32 indexIntoF ( Int32 indx, Int32 *cftab )
  2289. {
  2290.    Int32 nb, na, mid;
  2291.    nb = 0;
  2292.    na = 256;
  2293.    do {
  2294.       mid = (nb + na) >> 1;
  2295.       if (indx >= cftab[mid]) nb = mid; else na = mid;
  2296.    }
  2297.    while (na - nb != 1);
  2298.    return nb;
  2299. }
  2300.  
  2301.  
  2302. #define GET_SMALL(cccc)                     \
  2303.                                             \
  2304.       cccc = indexIntoF ( tPos, cftab );    \
  2305.       tPos = GET_LL(tPos);
  2306.  
  2307.  
  2308. void undoReversibleTransformation_small ( FILE* dst )
  2309. {
  2310.    Int32  cftab[257], cftabAlso[257];
  2311.    Int32  i, j, tmp, tPos;
  2312.    UChar  ch;
  2313.  
  2314.    /*--
  2315.       We assume here that the global array unzftab will
  2316.       already be holding the frequency counts for
  2317.       ll8[0 .. last].
  2318.    --*/
  2319.  
  2320.    /*-- Set up cftab to facilitate generation of indexIntoF --*/
  2321.    cftab[0] = 0;
  2322.    for (i = 1; i <= 256; i++) cftab[i] = unzftab[i-1];
  2323.    for (i = 1; i <= 256; i++) cftab[i] += cftab[i-1];
  2324.  
  2325.    /*-- Make a copy of it, used in generation of T --*/
  2326.    for (i = 0; i <= 256; i++) cftabAlso[i] = cftab[i];
  2327.  
  2328.    /*-- compute the T vector --*/
  2329.    for (i = 0; i <= last; i++) {
  2330.       ch = (UChar)ll16[i];
  2331.       SET_LL(i, cftabAlso[ch]);
  2332.       cftabAlso[ch]++;
  2333.    }
  2334.  
  2335.    /*--
  2336.       Compute T^(-1) by pointer reversal on T.  This is rather
  2337.       subtle, in that, if the original block was two or more
  2338.       (in general, N) concatenated copies of the same thing,
  2339.       the T vector will consist of N cycles, each of length
  2340.       blocksize / N, and decoding will involve traversing one
  2341.       of these cycles N times.  Which particular cycle doesn't
  2342.       matter -- they are all equivalent.  The tricky part is to
  2343.       make sure that the pointer reversal creates a correct
  2344.       reversed cycle for us to traverse.  So, the code below
  2345.       simply reverses whatever cycle origPtr happens to fall into,
  2346.       without regard to the cycle length.  That gives one reversed
  2347.       cycle, which for normal blocks, is the entire block-size long.
  2348.       For repeated blocks, it will be interspersed with the other
  2349.       N-1 non-reversed cycles.  Providing that the F-subscripting
  2350.       phase which follows starts at origPtr, all then works ok.
  2351.    --*/
  2352.    i = origPtr;
  2353.    j = GET_LL(i);
  2354.    do {
  2355.       tmp = GET_LL(j);
  2356.       SET_LL(j, i);
  2357.       i = j;
  2358.       j = tmp;
  2359.    }
  2360.       while (i != origPtr);
  2361.  
  2362.    /*--
  2363.       We recreate the original by subscripting F through T^(-1).
  2364.       The run-length-decoder below requires characters incrementally,
  2365.       so tPos is set to a starting value, and is updated by
  2366.       the GET_SMALL macro.
  2367.    --*/
  2368.    tPos   = origPtr;
  2369.  
  2370.    /*-------------------------------------------------*/
  2371.    /*--
  2372.       This is pretty much a verbatim copy of the
  2373.       run-length decoder present in the distribution
  2374.       bzip-0.21; it has to be here to avoid creating
  2375.       block[] as an intermediary structure.  As in 0.21,
  2376.       this code derives from some sent to me by
  2377.       Christian von Roques.
  2378.  
  2379.       It allows dst==NULL, so as to support the test (-t)
  2380.       option without slowing down the fast decompression
  2381.       code.
  2382.    --*/
  2383.    {
  2384.       IntNative retVal;
  2385.       Int32     i2, count, chPrev, ch2;
  2386.       UInt32    localCrc;
  2387.  
  2388.       count    = 0;
  2389.       i2       = 0;
  2390.       ch2      = 256;   /*-- not a char and not EOF --*/
  2391.       localCrc = getGlobalCRC();
  2392.  
  2393.       {
  2394.          RAND_DECLS;
  2395.          while ( i2 <= last ) {
  2396.             chPrev = ch2;
  2397.             GET_SMALL(ch2);
  2398.             if (blockRandomised) {
  2399.                RAND_UPD_MASK;
  2400.                ch2 ^= (UInt32)RAND_MASK;
  2401.             }
  2402.             i2++;
  2403.    
  2404.             if (dst)
  2405.                retVal = putc ( ch2, dst );
  2406.    
  2407.             UPDATE_CRC ( localCrc, (UChar)ch2 );
  2408.    
  2409.             if (ch2 != chPrev) {
  2410.                count = 1;
  2411.             } else {
  2412.                count++;
  2413.                if (count >= 4) {
  2414.                   Int32 j2;
  2415.                   UChar z;
  2416.                   GET_SMALL(z);
  2417.                   if (blockRandomised) {
  2418.                      RAND_UPD_MASK;
  2419.                      z ^= RAND_MASK;
  2420.                   }
  2421.                   for (j2 = 0;  j2 < (Int32)z;  j2++) {
  2422.                      if (dst) retVal = putc (ch2, dst);
  2423.                      UPDATE_CRC ( localCrc, (UChar)ch2 );
  2424.                   }
  2425.                   i2++;
  2426.                   count = 0;
  2427.                }
  2428.             }
  2429.          }
  2430.       }
  2431.  
  2432.       setGlobalCRC ( localCrc );
  2433.    }
  2434.    /*-- end of the in-line run-length-decoder. --*/
  2435. }
  2436. #undef GET_SMALL
  2437.  
  2438.  
  2439. /*---------------------------------------------*/
  2440.  
  2441. #define GET_FAST(cccc)                       \
  2442.                                              \
  2443.       cccc = ll8[tPos];                      \
  2444.       tPos = tt[tPos];
  2445.  
  2446.  
  2447. void undoReversibleTransformation_fast ( FILE* dst )
  2448. {
  2449.    Int32  cftab[257];
  2450.    Int32  i, tPos;
  2451.    UChar  ch;
  2452.  
  2453.    /*--
  2454.       We assume here that the global array unzftab will
  2455.       already be holding the frequency counts for
  2456.       ll8[0 .. last].
  2457.    --*/
  2458.  
  2459.    /*-- Set up cftab to facilitate generation of T^(-1) --*/
  2460.    cftab[0] = 0;
  2461.    for (i = 1; i <= 256; i++) cftab[i] = unzftab[i-1];
  2462.    for (i = 1; i <= 256; i++) cftab[i] += cftab[i-1];
  2463.  
  2464.    /*-- compute the T^(-1) vector --*/
  2465.    for (i = 0; i <= last; i++) {
  2466.       ch = (UChar)ll8[i];
  2467.       tt[cftab[ch]] = i;
  2468.       cftab[ch]++;
  2469.    }
  2470.  
  2471.    /*--
  2472.       We recreate the original by subscripting L through T^(-1).
  2473.       The run-length-decoder below requires characters incrementally,
  2474.       so tPos is set to a starting value, and is updated by
  2475.       the GET_FAST macro.
  2476.    --*/
  2477.    tPos   = tt[origPtr];
  2478.  
  2479.    /*-------------------------------------------------*/
  2480.    /*--
  2481.       This is pretty much a verbatim copy of the
  2482.       run-length decoder present in the distribution
  2483.       bzip-0.21; it has to be here to avoid creating
  2484.       block[] as an intermediary structure.  As in 0.21,
  2485.       this code derives from some sent to me by
  2486.       Christian von Roques.
  2487.    --*/
  2488.    {
  2489.       IntNative retVal;
  2490.       Int32     i2, count, chPrev, ch2;
  2491.       UInt32    localCrc;
  2492.  
  2493.       count    = 0;
  2494.       i2       = 0;
  2495.       ch2      = 256;   /*-- not a char and not EOF --*/
  2496.       localCrc = getGlobalCRC();
  2497.  
  2498.       if (blockRandomised) {
  2499.          RAND_DECLS;
  2500.          while ( i2 <= last ) {
  2501.             chPrev = ch2;
  2502.             GET_FAST(ch2);
  2503.             RAND_UPD_MASK;
  2504.             ch2 ^= (UInt32)RAND_MASK;
  2505.             i2++;
  2506.    
  2507.             retVal = putc ( ch2, dst );
  2508.             UPDATE_CRC ( localCrc, (UChar)ch2 );
  2509.    
  2510.             if (ch2 != chPrev) {
  2511.                count = 1;
  2512.             } else {
  2513.                count++;
  2514.                if (count >= 4) {
  2515.                   Int32 j2;
  2516.                   UChar z;
  2517.                   GET_FAST(z);
  2518.                   RAND_UPD_MASK;
  2519.                   z ^= RAND_MASK;
  2520.                   for (j2 = 0;  j2 < (Int32)z;  j2++) {
  2521.                      retVal = putc (ch2, dst);
  2522.                      UPDATE_CRC ( localCrc, (UChar)ch2 );
  2523.                   }
  2524.                   i2++;
  2525.                   count = 0;
  2526.                }
  2527.             }
  2528.          }
  2529.  
  2530.       } else {
  2531.  
  2532.          while ( i2 <= last ) {
  2533.             chPrev = ch2;
  2534.             GET_FAST(ch2);
  2535.             i2++;
  2536.    
  2537.             retVal = putc ( ch2, dst );
  2538.             UPDATE_CRC ( localCrc, (UChar)ch2 );
  2539.    
  2540.             if (ch2 != chPrev) {
  2541.                count = 1;
  2542.             } else {
  2543.                count++;
  2544.                if (count >= 4) {
  2545.                   Int32 j2;
  2546.                   UChar z;
  2547.                   GET_FAST(z);
  2548.                   for (j2 = 0;  j2 < (Int32)z;  j2++) {
  2549.                      retVal = putc (ch2, dst);
  2550.                      UPDATE_CRC ( localCrc, (UChar)ch2 );
  2551.                   }
  2552.                   i2++;
  2553.                   count = 0;
  2554.                }
  2555.             }
  2556.          }
  2557.  
  2558.       }   /*-- if (blockRandomised) --*/
  2559.  
  2560.       setGlobalCRC ( localCrc );
  2561.    }
  2562.    /*-- end of the in-line run-length-decoder. --*/
  2563. }
  2564. #undef GET_FAST
  2565.  
  2566.  
  2567. /*---------------------------------------------------*/
  2568. /*--- The block loader and RLEr                   ---*/
  2569. /*---------------------------------------------------*/
  2570.  
  2571. /*---------------------------------------------*/
  2572. /*  Top 16:   run length, 1 to 255.
  2573. *   Lower 16: the char, or MY_EOF for EOF.
  2574. */
  2575.  
  2576. #define MY_EOF 257
  2577.  
  2578. INLINE Int32 getRLEpair ( FILE* src )
  2579. {
  2580.    Int32     runLength;
  2581.    IntNative ch, chLatest;
  2582.  
  2583.    ch = getc ( src );
  2584.  
  2585.    /*--- Because I have no idea what kind of a value EOF is. ---*/
  2586.    if (ch == EOF) {
  2587.       ERROR_IF_NOT_ZERO ( ferror(src));
  2588.       return (1 << 16) | MY_EOF;
  2589.    }
  2590.  
  2591.    runLength = 0;
  2592.    do {
  2593.       chLatest = getc ( src );
  2594.       runLength++;
  2595.       bytesIn++;
  2596.    }
  2597.       while (ch == chLatest && runLength < 255);
  2598.  
  2599.    if ( chLatest != EOF ) {
  2600.       if ( ungetc ( chLatest, src ) == EOF )
  2601.          panic ( "getRLEpair: ungetc failed" );
  2602.    } else {
  2603.       ERROR_IF_NOT_ZERO ( ferror(src) );
  2604.    }
  2605.  
  2606.    /*--- Conditional is just a speedup hack. ---*/
  2607.    if (runLength == 1) {
  2608.       UPDATE_CRC ( globalCrc, (UChar)ch );
  2609.       return (1 << 16) | ch;
  2610.    } else {
  2611.       Int32 i;
  2612.       for (i = 1; i <= runLength; i++)
  2613.          UPDATE_CRC ( globalCrc, (UChar)ch );
  2614.       return (runLength << 16) | ch;
  2615.    }
  2616. }
  2617.  
  2618.  
  2619. /*---------------------------------------------*/
  2620. void loadAndRLEsource ( FILE* src )
  2621. {
  2622.    Int32 ch, allowableBlockSize, i;
  2623.  
  2624.    last = -1;
  2625.    ch   = 0;
  2626.  
  2627.    for (i = 0; i < 256; i++) inUse[i] = False;
  2628.  
  2629.    /*--- 20 is just a paranoia constant ---*/
  2630.    allowableBlockSize = 100000 * blockSize100k - 20;
  2631.  
  2632.    while (last < allowableBlockSize && ch != MY_EOF) {
  2633.       Int32 rlePair, runLen;
  2634.       rlePair = getRLEpair ( src );
  2635.       ch      = rlePair & 0xFFFF;
  2636.       runLen  = (UInt32)rlePair >> 16;
  2637.  
  2638.       #if DEBUG
  2639.          assert (runLen >= 1 && runLen <= 255);
  2640.       #endif
  2641.  
  2642.       if (ch != MY_EOF) {
  2643.          inUse[ch] = True;
  2644.          switch (runLen) {
  2645.             case 1:
  2646.                last++; block[last] = (UChar)ch; break;
  2647.             case 2:
  2648.                last++; block[last] = (UChar)ch;
  2649.                last++; block[last] = (UChar)ch; break;
  2650.             case 3:
  2651.                last++; block[last] = (UChar)ch;
  2652.                last++; block[last] = (UChar)ch;
  2653.                last++; block[last] = (UChar)ch; break;
  2654.             default:
  2655.                inUse[runLen-4] = True;
  2656.                last++; block[last] = (UChar)ch;
  2657.                last++; block[last] = (UChar)ch;
  2658.                last++; block[last] = (UChar)ch;
  2659.                last++; block[last] = (UChar)ch;
  2660.                last++; block[last] = (UChar)(runLen-4); break;
  2661.          }
  2662.       }
  2663.    }
  2664. }
  2665.  
  2666.  
  2667. /*---------------------------------------------------*/
  2668. /*--- Processing of complete files and streams    ---*/
  2669. /*---------------------------------------------------*/
  2670.  
  2671. /*---------------------------------------------*/
  2672. void compressStream ( FILE *stream, FILE *zStream )
  2673. {
  2674.    IntNative  retVal;
  2675.    UInt32     blockCRC, combinedCRC;
  2676.    Int32      blockNo;
  2677.  
  2678.    blockNo  = 0;
  2679.    bytesIn  = 0;
  2680.    bytesOut = 0;
  2681.    nBlocksRandomised = 0;
  2682.  
  2683.    SET_BINARY_MODE(stream);
  2684.    SET_BINARY_MODE(zStream);
  2685.  
  2686.    ERROR_IF_NOT_ZERO ( ferror(stream) );
  2687.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2688.  
  2689.    bsSetStream ( zStream, True );
  2690.  
  2691.    /*--- Write `magic' bytes B and Z,
  2692.          then h indicating file-format == huffmanised,
  2693.          followed by a digit indicating blockSize100k.
  2694.    ---*/
  2695.    bsPutUChar ( 'B' );
  2696.    bsPutUChar ( 'Z' );
  2697.    bsPutUChar ( 'h' );
  2698.    bsPutUChar ( '0' + blockSize100k );
  2699.  
  2700.    combinedCRC = 0;
  2701.  
  2702.    if (verbosity >= 2) fprintf ( stderr, "\n" );
  2703.  
  2704.    while (True) {
  2705.  
  2706.       blockNo++;
  2707.       initialiseCRC ();
  2708.       loadAndRLEsource ( stream );
  2709.       ERROR_IF_NOT_ZERO ( ferror(stream) );
  2710.       if (last == -1) break;
  2711.  
  2712.       blockCRC = getFinalCRC ();
  2713.       combinedCRC = (combinedCRC << 1) | (combinedCRC >> 31);
  2714.       combinedCRC ^= blockCRC;
  2715.  
  2716.       if (verbosity >= 2)
  2717.          fprintf ( stderr, "    block %d: crc = 0x%8x, combined CRC = 0x%8x, size = %d",
  2718.                            blockNo, blockCRC, combinedCRC, last+1 );
  2719.  
  2720.       /*-- sort the block and establish posn of original string --*/
  2721.       doReversibleTransformation ();
  2722.  
  2723.       /*--
  2724.         A 6-byte block header, the value chosen arbitrarily
  2725.         as 0x314159265359 :-).  A 32 bit value does not really
  2726.         give a strong enough guarantee that the value will not
  2727.         appear by chance in the compressed datastream.  Worst-case
  2728.         probability of this event, for a 900k block, is about
  2729.         2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 bits.
  2730.         For a compressed file of size 100Gb -- about 100000 blocks --
  2731.         only a 48-bit marker will do.  NB: normal compression/
  2732.         decompression do *not* rely on these statistical properties.
  2733.         They are only important when trying to recover blocks from
  2734.         damaged files.
  2735.       --*/
  2736.       bsPutUChar ( 0x31 ); bsPutUChar ( 0x41 );
  2737.       bsPutUChar ( 0x59 ); bsPutUChar ( 0x26 );
  2738.       bsPutUChar ( 0x53 ); bsPutUChar ( 0x59 );
  2739.  
  2740.       /*-- Now the block's CRC, so it is in a known place. --*/
  2741.       bsPutUInt32 ( blockCRC );
  2742.  
  2743.       /*-- Now a single bit indicating randomisation. --*/
  2744.       if (blockRandomised) {
  2745.          bsW(1,1); nBlocksRandomised++;
  2746.       } else
  2747.          bsW(1,0);
  2748.  
  2749.       /*-- Finally, block's contents proper. --*/
  2750.       moveToFrontCodeAndSend ();
  2751.  
  2752.       ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2753.    }
  2754.  
  2755.    if (verbosity >= 2 && nBlocksRandomised > 0)
  2756.       fprintf ( stderr, "    %d block%s needed randomisation\n", 
  2757.                         nBlocksRandomised,
  2758.                         nBlocksRandomised == 1 ? "" : "s" );
  2759.  
  2760.    /*--
  2761.       Now another magic 48-bit number, 0x177245385090, to
  2762.       indicate the end of the last block.  (sqrt(pi), if
  2763.       you want to know.  I did want to use e, but it contains
  2764.       too much repetition -- 27 18 28 18 28 46 -- for me
  2765.       to feel statistically comfortable.  Call me paranoid.)
  2766.    --*/
  2767.  
  2768.    bsPutUChar ( 0x17 ); bsPutUChar ( 0x72 );
  2769.    bsPutUChar ( 0x45 ); bsPutUChar ( 0x38 );
  2770.    bsPutUChar ( 0x50 ); bsPutUChar ( 0x90 );
  2771.  
  2772.    bsPutUInt32 ( combinedCRC );
  2773.    if (verbosity >= 2)
  2774.       fprintf ( stderr, "    final combined CRC = 0x%x\n   ", combinedCRC );
  2775.  
  2776.    /*-- Close the files in an utterly paranoid way. --*/
  2777.    bsFinishedWithStream ();
  2778.  
  2779.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2780.    retVal = fflush ( zStream );
  2781.    ERROR_IF_EOF ( retVal );
  2782.    retVal = fclose ( zStream );
  2783.    ERROR_IF_EOF ( retVal );
  2784.  
  2785.    ERROR_IF_NOT_ZERO ( ferror(stream) );
  2786.    retVal = fclose ( stream );
  2787.    ERROR_IF_EOF ( retVal );
  2788.  
  2789.    if (bytesIn == 0) bytesIn = 1;
  2790.    if (bytesOut == 0) bytesOut = 1;
  2791.  
  2792.    if (verbosity >= 1)
  2793.       fprintf ( stderr, "%6.3f:1, %6.3f bits/byte, "
  2794.                         "%5.2f%% saved, %d in, %d out.\n",
  2795.                 (float)bytesIn / (float)bytesOut,
  2796.                 (8.0 * (float)bytesOut) / (float)bytesIn,
  2797.                 100.0 * (1.0 - (float)bytesOut / (float)bytesIn),
  2798.                 bytesIn,
  2799.                 bytesOut
  2800.               );
  2801. }
  2802.  
  2803.  
  2804. /*---------------------------------------------*/
  2805. Bool uncompressStream ( FILE *zStream, FILE *stream )
  2806. {
  2807.    UChar      magic1, magic2, magic3, magic4;
  2808.    UChar      magic5, magic6;
  2809.    UInt32     storedBlockCRC, storedCombinedCRC;
  2810.    UInt32     computedBlockCRC, computedCombinedCRC;
  2811.    Int32      currBlockNo;
  2812.    IntNative  retVal;
  2813.  
  2814.    SET_BINARY_MODE(stream);
  2815.    SET_BINARY_MODE(zStream);
  2816.  
  2817.    ERROR_IF_NOT_ZERO ( ferror(stream) );
  2818.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2819.  
  2820.    bsSetStream ( zStream, False );
  2821.  
  2822.    /*--
  2823.       A bad magic number is `recoverable from';
  2824.       return with False so the caller skips the file.
  2825.    --*/
  2826.    magic1 = bsGetUChar ();
  2827.    magic2 = bsGetUChar ();
  2828.    magic3 = bsGetUChar ();
  2829.    magic4 = bsGetUChar ();
  2830.    if (magic1 != 'B' ||
  2831.        magic2 != 'Z' ||
  2832.        magic3 != 'h' ||
  2833.        magic4 < '1'  ||
  2834.        magic4 > '9') {
  2835.      bsFinishedWithStream();
  2836.      retVal = fclose ( stream );
  2837.      ERROR_IF_EOF ( retVal );
  2838.      return False;
  2839.    }
  2840.  
  2841.    setDecompressStructureSizes ( magic4 - '0' );
  2842.    computedCombinedCRC = 0;
  2843.  
  2844.    if (verbosity >= 2) fprintf ( stderr, "\n    " );
  2845.    currBlockNo = 0;
  2846.  
  2847.    while (True) {
  2848.       magic1 = bsGetUChar ();
  2849.       magic2 = bsGetUChar ();
  2850.       magic3 = bsGetUChar ();
  2851.       magic4 = bsGetUChar ();
  2852.       magic5 = bsGetUChar ();
  2853.       magic6 = bsGetUChar ();
  2854.       if (magic1 == 0x17 && magic2 == 0x72 &&
  2855.           magic3 == 0x45 && magic4 == 0x38 &&
  2856.           magic5 == 0x50 && magic6 == 0x90) break;
  2857.  
  2858.       if (magic1 != 0x31 || magic2 != 0x41 ||
  2859.           magic3 != 0x59 || magic4 != 0x26 ||
  2860.           magic5 != 0x53 || magic6 != 0x59) badBlockHeader();
  2861.  
  2862.       storedBlockCRC = bsGetUInt32 ();
  2863.  
  2864.       if (bsR(1) == 1)
  2865.          blockRandomised = True; else
  2866.          blockRandomised = False;
  2867.  
  2868.       currBlockNo++;
  2869.       if (verbosity >= 2)
  2870.          fprintf ( stderr, "[%d: huff+mtf ", currBlockNo );
  2871.       getAndMoveToFrontDecode ();
  2872.       ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2873.  
  2874.       initialiseCRC();
  2875.       if (verbosity >= 2) fprintf ( stderr, "rt+rld" );
  2876.       if (smallMode)
  2877.          undoReversibleTransformation_small ( stream );
  2878.          else
  2879.          undoReversibleTransformation_fast  ( stream );
  2880.  
  2881.       ERROR_IF_NOT_ZERO ( ferror(stream) );
  2882.  
  2883.       computedBlockCRC = getFinalCRC();
  2884.       if (verbosity >= 3)
  2885.          fprintf ( stderr, " {0x%x, 0x%x}", storedBlockCRC, computedBlockCRC );
  2886.       if (verbosity >= 2) fprintf ( stderr, "] " );
  2887.  
  2888.       /*-- A bad CRC is considered a fatal error. --*/
  2889.       if (storedBlockCRC != computedBlockCRC)
  2890.          crcError ( storedBlockCRC, computedBlockCRC );
  2891.  
  2892.       computedCombinedCRC = (computedCombinedCRC << 1) | (computedCombinedCRC >> 31);
  2893.       computedCombinedCRC ^= computedBlockCRC;
  2894.    };
  2895.  
  2896.    if (verbosity >= 2) fprintf ( stderr, "\n    " );
  2897.  
  2898.    storedCombinedCRC  = bsGetUInt32 ();
  2899.    if (verbosity >= 2)
  2900.       fprintf ( stderr,
  2901.                 "combined CRCs: stored = 0x%x, computed = 0x%x\n    ",
  2902.                 storedCombinedCRC, computedCombinedCRC );
  2903.    if (storedCombinedCRC != computedCombinedCRC)
  2904.       crcError ( storedCombinedCRC, computedCombinedCRC );
  2905.  
  2906.  
  2907.    bsFinishedWithStream ();
  2908.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2909.    retVal = fclose ( zStream );
  2910.    ERROR_IF_EOF ( retVal );
  2911.  
  2912.    ERROR_IF_NOT_ZERO ( ferror(stream) );
  2913.    retVal = fflush ( stream );
  2914.    ERROR_IF_NOT_ZERO ( retVal );
  2915.    if (stream != stdout) {
  2916.       retVal = fclose ( stream );
  2917.       ERROR_IF_EOF ( retVal );
  2918.    }
  2919.    return True;
  2920. }
  2921.  
  2922.  
  2923. /*---------------------------------------------*/
  2924. Bool testStream ( FILE *zStream )
  2925. {
  2926.    UChar      magic1, magic2, magic3, magic4;
  2927.    UChar      magic5, magic6;
  2928.    UInt32     storedBlockCRC, storedCombinedCRC;
  2929.    UInt32     computedBlockCRC, computedCombinedCRC;
  2930.    Int32      currBlockNo;
  2931.    IntNative  retVal;
  2932.  
  2933.    SET_BINARY_MODE(zStream);
  2934.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2935.  
  2936.    bsSetStream ( zStream, False );
  2937.  
  2938.    magic1 = bsGetUChar ();
  2939.    magic2 = bsGetUChar ();
  2940.    magic3 = bsGetUChar ();
  2941.    magic4 = bsGetUChar ();
  2942.    if (magic1 != 'B' ||
  2943.        magic2 != 'Z' ||
  2944.        magic3 != 'h' ||
  2945.        magic4 < '1'  ||
  2946.        magic4 > '9') {
  2947.      bsFinishedWithStream();
  2948.      fclose ( zStream );
  2949.      fprintf ( stderr, "\n%s: bad magic number (ie, not created by bzip2)\n",
  2950.                        inName );
  2951.      return False;
  2952.    }
  2953.  
  2954.    smallMode = True;
  2955.    setDecompressStructureSizes ( magic4 - '0' );
  2956.    computedCombinedCRC = 0;
  2957.  
  2958.    if (verbosity >= 2) fprintf ( stderr, "\n" );
  2959.    currBlockNo = 0;
  2960.  
  2961.    while (True) {
  2962.       magic1 = bsGetUChar ();
  2963.       magic2 = bsGetUChar ();
  2964.       magic3 = bsGetUChar ();
  2965.       magic4 = bsGetUChar ();
  2966.       magic5 = bsGetUChar ();
  2967.       magic6 = bsGetUChar ();
  2968.       if (magic1 == 0x17 && magic2 == 0x72 &&
  2969.           magic3 == 0x45 && magic4 == 0x38 &&
  2970.           magic5 == 0x50 && magic6 == 0x90) break;
  2971.  
  2972.       currBlockNo++;
  2973.       if (magic1 != 0x31 || magic2 != 0x41 ||
  2974.           magic3 != 0x59 || magic4 != 0x26 ||
  2975.           magic5 != 0x53 || magic6 != 0x59) {
  2976.          bsFinishedWithStream();
  2977.          fclose ( zStream );
  2978.          fprintf ( stderr,
  2979.                    "\n%s, block %d: bad header (not == 0x314159265359)\n",
  2980.                    inName, currBlockNo );
  2981.          return False;
  2982.       }
  2983.       storedBlockCRC = bsGetUInt32 ();
  2984.  
  2985.       if (bsR(1) == 1)
  2986.          blockRandomised = True; else
  2987.          blockRandomised = False;
  2988.  
  2989.       if (verbosity >= 2)
  2990.          fprintf ( stderr, "    block [%d: huff+mtf ", currBlockNo );
  2991.       getAndMoveToFrontDecode ();
  2992.       ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2993.  
  2994.       initialiseCRC();
  2995.       if (verbosity >= 2) fprintf ( stderr, "rt+rld" );
  2996.       undoReversibleTransformation_small ( NULL );
  2997.  
  2998.       computedBlockCRC = getFinalCRC();
  2999.       if (verbosity >= 3)
  3000.          fprintf ( stderr, " {0x%x, 0x%x}", storedBlockCRC, computedBlockCRC );
  3001.       if (verbosity >= 2) fprintf ( stderr, "] " );
  3002.  
  3003.       if (storedBlockCRC != computedBlockCRC) {
  3004.          bsFinishedWithStream();
  3005.          fclose ( zStream );
  3006.          fprintf ( stderr, "\n%s, block %d: computed CRC does not match stored one\n",
  3007.                            inName, currBlockNo );
  3008.          return False;
  3009.       }
  3010.  
  3011.       if (verbosity >= 2) fprintf ( stderr, "ok\n" );
  3012.       computedCombinedCRC = (computedCombinedCRC << 1) | (computedCombinedCRC >> 31);
  3013.       computedCombinedCRC ^= computedBlockCRC;
  3014.    };
  3015.  
  3016.    storedCombinedCRC  = bsGetUInt32 ();
  3017.    if (verbosity >= 2)
  3018.       fprintf ( stderr,
  3019.                 "    combined CRCs: stored = 0x%x, computed = 0x%x\n    ",
  3020.                 storedCombinedCRC, computedCombinedCRC );
  3021.    if (storedCombinedCRC != computedCombinedCRC) {
  3022.       bsFinishedWithStream();
  3023.       fclose ( zStream );
  3024.       fprintf ( stderr, "\n%s: computed CRC does not match stored one\n",
  3025.                         inName );
  3026.       return False;
  3027.    }
  3028.  
  3029.    bsFinishedWithStream ();
  3030.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  3031.    retVal = fclose ( zStream );
  3032.    ERROR_IF_EOF ( retVal );
  3033.    return True;
  3034. }
  3035.  
  3036.  
  3037.  
  3038. /*---------------------------------------------------*/
  3039. /*--- Error [non-] handling grunge                ---*/
  3040. /*---------------------------------------------------*/
  3041.  
  3042. /*---------------------------------------------*/
  3043. void cadvise ( void )
  3044. {
  3045.    fprintf (
  3046.       stderr,
  3047.       "\nIt is possible that the compressed file(s) have become corrupted.\n"
  3048.         "You can use the -tvv option to test integrity of such files.\n\n"
  3049.         "You can use the `bzip2recover' program to *attempt* to recover\n"
  3050.         "data from undamaged sections of corrupted files.\n\n"
  3051.     );
  3052. }
  3053.  
  3054.  
  3055. /*---------------------------------------------*/
  3056. void showFileNames ( void )
  3057. {
  3058.    fprintf (
  3059.       stderr,
  3060.       "\tInput file = %s, output file = %s\n",
  3061.       inName==NULL  ? "(null)" : inName,
  3062.       outName==NULL ? "(null)" : outName
  3063.    );
  3064. }
  3065.  
  3066.  
  3067. /*---------------------------------------------*/
  3068. void cleanUpAndFail ( Int32 ec )
  3069. {
  3070.    IntNative retVal;
  3071.  
  3072.    if ( srcMode == SM_F2F && opMode != OM_TEST ) {
  3073.       fprintf ( stderr, "%s: Deleting output file %s, if it exists.\n",
  3074.                 progName,
  3075.                 outName==NULL ? "(null)" : outName );
  3076.       if (outputHandleJustInCase != NULL)
  3077.          fclose ( outputHandleJustInCase );
  3078.       retVal = remove ( outName );
  3079.       if (retVal != 0)
  3080.          fprintf ( stderr,
  3081.                    "%s: WARNING: deletion of output file (apparently) failed.\n",
  3082.                    progName );
  3083.    }
  3084.    if (numFileNames > 0 && numFilesProcessed < numFileNames) {
  3085.       fprintf ( stderr, 
  3086.                 "%s: WARNING: some files have not been processed:\n"
  3087.                 "\t%d specified on command line, %d not processed yet.\n\n",
  3088.                 progName, numFileNames, 
  3089.                           numFileNames - numFilesProcessed );
  3090.    }
  3091.    exit ( ec );
  3092. }
  3093.  
  3094.  
  3095. /*---------------------------------------------*/
  3096. void panic ( Char* s )
  3097. {
  3098.    fprintf ( stderr,
  3099.              "\n%s: PANIC -- internal consistency error:\n"
  3100.              "\t%s\n"
  3101.              "\tThis is a BUG.  Please report it to me at:\n"
  3102.              "\tjseward@acm.org\n",
  3103.              progName, s );
  3104.    showFileNames();
  3105.    cleanUpAndFail( 3 );
  3106. }
  3107.  
  3108.  
  3109. /*---------------------------------------------*/
  3110. void badBGLengths ( void )
  3111. {
  3112.    fprintf ( stderr,
  3113.              "\n%s: error when reading background model code lengths,\n"
  3114.              "\twhich probably means the compressed file is corrupted.\n",
  3115.              progName );
  3116.    showFileNames();
  3117.    cadvise();
  3118.    cleanUpAndFail( 2 );
  3119. }
  3120.  
  3121.  
  3122. /*---------------------------------------------*/
  3123. void crcError ( UInt32 crcStored, UInt32 crcComputed )
  3124. {
  3125.    fprintf ( stderr,
  3126.              "\n%s: Data integrity error when decompressing.\n"
  3127.              "\tStored CRC = 0x%x, computed CRC = 0x%x\n",
  3128.              progName, crcStored, crcComputed );
  3129.    showFileNames();
  3130.    cadvise();
  3131.    cleanUpAndFail( 2 );
  3132. }
  3133.  
  3134.  
  3135. /*---------------------------------------------*/
  3136. void compressedStreamEOF ( void )
  3137. {
  3138.    fprintf ( stderr,
  3139.              "\n%s: Compressed file ends unexpectedly;\n\t"
  3140.              "perhaps it is corrupted?  *Possible* reason follows.\n",
  3141.              progName );
  3142.    perror ( progName );
  3143.    showFileNames();
  3144.    cadvise();
  3145.    cleanUpAndFail( 2 );
  3146. }
  3147.  
  3148.  
  3149. /*---------------------------------------------*/
  3150. void ioError ( )
  3151. {
  3152.    fprintf ( stderr,
  3153.              "\n%s: I/O or other error, bailing out.  Possible reason follows.\n",
  3154.              progName );
  3155.    perror ( progName );
  3156.    showFileNames();
  3157.    cleanUpAndFail( 1 );
  3158. }
  3159.  
  3160.  
  3161. /*---------------------------------------------*/
  3162. void blockOverrun ()
  3163. {
  3164.    fprintf ( stderr,
  3165.              "\n%s: block overrun during decompression,\n"
  3166.              "\twhich probably means the compressed file\n"
  3167.              "\tis corrupted.\n",
  3168.              progName );
  3169.    showFileNames();
  3170.    cadvise();
  3171.    cleanUpAndFail( 2 );
  3172. }
  3173.  
  3174.  
  3175. /*---------------------------------------------*/
  3176. void badBlockHeader ()
  3177. {
  3178.    fprintf ( stderr,
  3179.              "\n%s: bad block header in the compressed file,\n"
  3180.              "\twhich probably means it is corrupted.\n",
  3181.              progName );
  3182.    showFileNames();
  3183.    cadvise();
  3184.    cleanUpAndFail( 2 );
  3185. }
  3186.  
  3187.  
  3188. /*---------------------------------------------*/
  3189. void bitStreamEOF ()
  3190. {
  3191.    fprintf ( stderr,
  3192.              "\n%s: read past the end of compressed data,\n"
  3193.              "\twhich probably means it is corrupted.\n",
  3194.              progName );
  3195.    showFileNames();
  3196.    cadvise();
  3197.    cleanUpAndFail( 2 );
  3198. }
  3199.  
  3200.  
  3201. /*---------------------------------------------*/
  3202. void mySignalCatcher ( IntNative n )
  3203. {
  3204.    fprintf ( stderr,
  3205.              "\n%s: Control-C (or similar) caught, quitting.\n",
  3206.              progName );
  3207.    cleanUpAndFail(1);
  3208. }
  3209.  
  3210.  
  3211. /*---------------------------------------------*/
  3212. void mySIGSEGVorSIGBUScatcher ( IntNative n )
  3213. {
  3214.    if (opMode == OM_Z)
  3215.       fprintf ( stderr,
  3216.                 "\n%s: Caught a SIGSEGV or SIGBUS whilst compressing,\n"
  3217.                 "\twhich probably indicates a bug in bzip2.  Please\n"
  3218.                 "\treport it to me at: jseward@acm.org\n",
  3219.                 progName );
  3220.       else
  3221.       fprintf ( stderr,
  3222.                 "\n%s: Caught a SIGSEGV or SIGBUS whilst decompressing,\n"
  3223.                 "\twhich probably indicates that the compressed data\n"
  3224.                 "\tis corrupted.\n",
  3225.                 progName );
  3226.  
  3227.    showFileNames();
  3228.    if (opMode == OM_Z)
  3229.       cleanUpAndFail( 3 ); else
  3230.       { cadvise(); cleanUpAndFail( 2 ); }
  3231. }
  3232.  
  3233.  
  3234. /*---------------------------------------------*/
  3235. void uncompressOutOfMemory ( Int32 draw, Int32 blockSize )
  3236. {
  3237.    fprintf ( stderr,
  3238.              "\n%s: Can't allocate enough memory for decompression.\n"
  3239.              "\tRequested %d bytes for a block size of %d.\n"
  3240.              "\tTry selecting space-economic decompress (with flag -s)\n"
  3241.              "\tand failing that, find a machine with more memory.\n",
  3242.              progName, draw, blockSize );
  3243.    showFileNames();
  3244.    cleanUpAndFail(1);
  3245. }
  3246.  
  3247.  
  3248. /*---------------------------------------------*/
  3249. void compressOutOfMemory ( Int32 draw, Int32 blockSize )
  3250. {
  3251.    fprintf ( stderr,
  3252.              "\n%s: Can't allocate enough memory for compression.\n"
  3253.              "\tRequested %d bytes for a block size of %d.\n"
  3254.              "\tTry selecting a small block size (with flag -s).\n",
  3255.              progName, draw, blockSize );
  3256.    showFileNames();
  3257.    cleanUpAndFail(1);
  3258. }
  3259.  
  3260.  
  3261. /*---------------------------------------------------*/
  3262. /*--- The main driver machinery                   ---*/
  3263. /*---------------------------------------------------*/
  3264.  
  3265. /*---------------------------------------------*/
  3266. void pad ( Char *s )
  3267. {
  3268.    Int32 i;
  3269.    if ( (Int32)strlen(s) >= longestFileName ) return;
  3270.    for (i = 1; i <= longestFileName - (Int32)strlen(s); i++)
  3271.       fprintf ( stderr, " " );
  3272. }
  3273.  
  3274.  
  3275. /*---------------------------------------------*/
  3276. Bool fileExists ( Char* name )
  3277. {
  3278.    FILE *tmp   = fopen ( name, "rb" );
  3279.    Bool exists = (tmp != NULL);
  3280.    if (tmp != NULL) fclose ( tmp );
  3281.    return exists;
  3282. }
  3283.  
  3284.  
  3285. /*---------------------------------------------*/
  3286. /*--
  3287.   if in doubt, return True
  3288. --*/
  3289.  
  3290. Bool notABogStandardFile ( Char* name )
  3291. {
  3292.    IntNative      i;
  3293.    struct MY_STAT statBuf;
  3294.  
  3295.    i = MY_LSTAT ( name, &statBuf );
  3296.    if (i != 0) return True;
  3297. #ifndef BZ_AMIGA
  3298.    if (MY_S_IFREG(statBuf.st_mode)) return False;
  3299.    return True;
  3300. #else
  3301.    return False;
  3302. #endif
  3303. }
  3304.  
  3305.  
  3306. /*---------------------------------------------*/
  3307. void copyDateAndPermissions ( Char *srcName, Char *dstName )
  3308. {
  3309.    #if BZ_UNIX
  3310.    IntNative      retVal;
  3311.    struct MY_STAT statBuf;
  3312.    struct utimbuf uTimBuf;
  3313.  
  3314.    retVal = MY_LSTAT ( srcName, &statBuf );
  3315.    ERROR_IF_NOT_ZERO ( retVal );
  3316.    uTimBuf.actime = statBuf.st_atime;
  3317.    uTimBuf.modtime = statBuf.st_mtime;
  3318.  
  3319.    retVal = chmod ( dstName, statBuf.st_mode );
  3320.    ERROR_IF_NOT_ZERO ( retVal );
  3321.    retVal = utime ( dstName, &uTimBuf );
  3322.    ERROR_IF_NOT_ZERO ( retVal );
  3323.    #endif
  3324. }
  3325.  
  3326.  
  3327. /*---------------------------------------------*/
  3328. Bool endsInBz2 ( Char* name )
  3329. {
  3330.    Int32 n = strlen ( name );
  3331.    if (n <= 4) return False;
  3332.    return
  3333.       (name[n-4] == '.' &&
  3334.        name[n-3] == 'b' &&
  3335.        name[n-2] == 'z' &&
  3336.        name[n-1] == '2');
  3337. }
  3338.  
  3339.  
  3340. /*---------------------------------------------*/
  3341. Bool containsDubiousChars ( Char* name )
  3342. {
  3343.    Bool cdc = False;
  3344.    for (; *name != '\0'; name++)
  3345.       if (*name == '?' || *name == '*') cdc = True;
  3346.    return cdc;
  3347. }
  3348.  
  3349.  
  3350. /*---------------------------------------------*/
  3351. void compress ( Char *name )
  3352. {
  3353.    FILE *inStr;
  3354.    FILE *outStr;
  3355.  
  3356.    if (name == NULL && srcMode != SM_I2O)
  3357.       panic ( "compress: bad modes\n" );
  3358.  
  3359.    switch (srcMode) {
  3360.       case SM_I2O: strcpy ( inName, "(stdin)" );
  3361.                    strcpy ( outName, "(stdout)" ); break;
  3362.       case SM_F2F: strcpy ( inName, name );
  3363.                    strcpy ( outName, name );
  3364.                    strcat ( outName, ".bz2" ); break;
  3365.       case SM_F2O: strcpy ( inName, name );
  3366.                    strcpy ( outName, "(stdout)" ); break;
  3367.    }
  3368.  
  3369.    if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) {
  3370.       fprintf ( stderr, "%s: There are no files matching `%s'.\n",
  3371.       progName, inName );
  3372.       return;
  3373.    }
  3374.    if ( srcMode != SM_I2O && !fileExists ( inName ) ) {
  3375.       fprintf ( stderr, "%s: Input file %s doesn't exist, skipping.\n",
  3376.                 progName, inName );
  3377.       return;
  3378.    }
  3379.    if ( srcMode != SM_I2O && endsInBz2 ( inName )) {
  3380.       fprintf ( stderr, "%s: Input file name %s ends in `.bz2', skipping.\n",
  3381.                 progName, inName );
  3382.       return;
  3383.    }
  3384.    if ( srcMode != SM_I2O && notABogStandardFile ( inName )) {
  3385.       fprintf ( stderr, "%s: Input file %s is not a normal file, skipping.\n",
  3386.                 progName, inName );
  3387.       return;
  3388.    }
  3389.    if ( srcMode == SM_F2F && fileExists ( outName ) ) {
  3390.       fprintf ( stderr, "%s: Output file %s already exists, skipping.\n",
  3391.                 progName, outName );
  3392.       return;
  3393.    }
  3394.  
  3395.    inStr = fopen ( inName, "rb" );
  3396.  
  3397.    if ( inStr == NULL ) {
  3398.             fprintf ( stderr, "%s: Can't open input file %s, skipping.\n",
  3399.                       progName, inName );
  3400.             return;
  3401.            }
  3402.    strcpy(outName,inName);
  3403.    strcat(outName,".bz2");
  3404.    outStr = fopen ( outName, "wb" );
  3405.  
  3406.    if (!outStr)
  3407.    {
  3408.     fprintf(stderr,"%s: Can't open output file %s, skipping.\n",progName,outName);
  3409.    }
  3410.  
  3411.    if (verbosity >= 1) {
  3412.       fprintf ( stderr,  "  %s: ", inName );
  3413.       pad ( inName );
  3414.       fflush ( stderr );
  3415.    }
  3416.  
  3417.    /*--- Now the input and output handles are sane.  Do the Biz. ---*/
  3418.    outputHandleJustInCase = outStr;
  3419.    compressStream ( inStr, outStr );
  3420.    outputHandleJustInCase = NULL;
  3421.  
  3422.    /*--- If there was an I/O error, we won't get here. ---*/
  3423.    if ( srcMode == SM_F2F ) {
  3424.       copyDateAndPermissions ( inName, outName );
  3425.       if ( !keepInputFiles ) {
  3426.          IntNative retVal = remove ( inName );
  3427.          ERROR_IF_NOT_ZERO ( retVal );
  3428.       }
  3429.    }
  3430. }
  3431.  
  3432.  
  3433. /*---------------------------------------------*/
  3434. void uncompress ( Char *name )
  3435. {
  3436.    FILE *inStr;
  3437.    FILE *outStr;
  3438.    Bool magicNumberOK;
  3439.  
  3440.    if (name == NULL && srcMode != SM_I2O)
  3441.       panic ( "uncompress: bad modes\n" );
  3442.  
  3443.    switch (srcMode) {
  3444.       case SM_I2O: strcpy ( inName, "(stdin)" );
  3445.                    strcpy ( outName, "(stdout)" ); break;
  3446.       case SM_F2F: strcpy ( inName, name );
  3447.                    strcpy ( outName, name );
  3448.                    if (endsInBz2 ( outName ))
  3449.                       outName [ strlen ( outName ) - 4 ] = '\0';
  3450.                    break;
  3451.       case SM_F2O: strcpy ( inName, name );
  3452.                    strcpy ( outName, "(stdout)" ); break;
  3453.    }
  3454.  
  3455.    if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) {
  3456.       fprintf ( stderr, "%s: There are no files matching `%s'.\n",
  3457.                 progName, inName );
  3458.       return;
  3459.    }
  3460.    if ( srcMode != SM_I2O && !fileExists ( inName ) ) {
  3461.       fprintf ( stderr, "%s: Input file %s doesn't exist, skipping.\n",
  3462.                 progName, inName );
  3463.       return;
  3464.    }
  3465.    if ( srcMode != SM_I2O && !endsInBz2 ( inName )) {
  3466.       fprintf ( stderr,
  3467.                 "%s: Input file name %s doesn't end in `.bz2', skipping.\n",
  3468.                 progName, inName );
  3469.       return;
  3470.    }
  3471.    if ( srcMode != SM_I2O && notABogStandardFile ( inName )) {
  3472.       fprintf ( stderr, "%s: Input file %s is not a normal file, skipping.\n",
  3473.                 progName, inName );
  3474.       return;
  3475.    }
  3476.    if ( srcMode == SM_F2F && fileExists ( outName ) ) {
  3477.       fprintf ( stderr, "%s: Output file %s already exists, skipping.\n",
  3478.                 progName, outName );
  3479.       return;
  3480.    }
  3481.  
  3482.    switch ( srcMode ) {
  3483.  
  3484.       case SM_I2O:
  3485.          inStr = stdin;
  3486.          outStr = stdout;
  3487.          if ( isatty ( fileno ( stdin ) ) ) {
  3488.             fprintf ( stderr,
  3489.                       "%s: I won't read compressed data from a terminal.\n",
  3490.                       progName );
  3491.             fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
  3492.                               progName, progName );
  3493.             return;
  3494.          };
  3495.          break;
  3496.  
  3497.       case SM_F2O:
  3498.          inStr = fopen ( inName, "rb" );
  3499.          outStr = stdout;
  3500.          if ( inStr == NULL ) {
  3501.             fprintf ( stderr, "%s: Can't open input file %s, skipping.\n",
  3502.                       progName, inName );
  3503.             return;
  3504.          };
  3505.          break;
  3506.  
  3507.       case SM_F2F:
  3508.          inStr = fopen ( inName, "rb" );
  3509.          outStr = fopen ( outName, "wb" );
  3510.          if ( outStr == NULL) {
  3511.             fprintf ( stderr, "%s: Can't create output file %s, skipping.\n",
  3512.                       progName, outName );
  3513.             return;
  3514.          }
  3515.          if ( inStr == NULL ) {
  3516.             fprintf ( stderr, "%s: Can't open input file %s, skipping.\n",
  3517.                       progName, inName );
  3518.             return;
  3519.          };
  3520.          break;
  3521.  
  3522.       default:
  3523.          panic ( "uncompress: bad srcMode" );
  3524.          break;
  3525.    }
  3526.  
  3527.    if (verbosity >= 1) {
  3528.       fprintf ( stderr, "  %s: ", inName );
  3529.       pad ( inName );
  3530.       fflush ( stderr );
  3531.    }
  3532.  
  3533.    /*--- Now the input and output handles are sane.  Do the Biz. ---*/
  3534.    outputHandleJustInCase = outStr;
  3535.    magicNumberOK = uncompressStream ( inStr, outStr );
  3536.    outputHandleJustInCase = NULL;
  3537.  
  3538.    /*--- If there was an I/O error, we won't get here. ---*/
  3539.    if ( magicNumberOK ) {
  3540.       if ( srcMode == SM_F2F ) {
  3541.          copyDateAndPermissions ( inName, outName );
  3542.          if ( !keepInputFiles ) {
  3543.             IntNative retVal = remove ( inName );
  3544.             ERROR_IF_NOT_ZERO ( retVal );
  3545.          }
  3546.       }
  3547.    } else {
  3548.       if ( srcMode == SM_F2F ) {
  3549.          IntNative retVal = remove ( outName );
  3550.          ERROR_IF_NOT_ZERO ( retVal );
  3551.       }
  3552.    }
  3553.  
  3554.    if ( magicNumberOK ) {
  3555.       if (verbosity >= 1)
  3556.          fprintf ( stderr, "done\n" );
  3557.    } else {
  3558.       if (verbosity >= 1)
  3559.          fprintf ( stderr, "not a bzip2 file, skipping.\n" ); else
  3560.          fprintf ( stderr,
  3561.                    "%s: %s is not a bzip2 file, skipping.\n",
  3562.                    progName, inName );
  3563.    }
  3564.  
  3565. }
  3566.  
  3567.  
  3568. /*---------------------------------------------*/
  3569. void testf ( Char *name )
  3570. {
  3571.    FILE *inStr;
  3572.    Bool allOK;
  3573.  
  3574.    if (name == NULL && srcMode != SM_I2O)
  3575.       panic ( "testf: bad modes\n" );
  3576.  
  3577.    strcpy ( outName, "(none)" );
  3578.    switch (srcMode) {
  3579.       case SM_I2O: strcpy ( inName, "(stdin)" ); break;
  3580.       case SM_F2F: strcpy ( inName, name ); break;
  3581.       case SM_F2O: strcpy ( inName, name ); break;
  3582.    }
  3583.  
  3584.    if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) {
  3585.       fprintf ( stderr, "%s: There are no files matching `%s'.\n",
  3586.                 progName, inName );
  3587.       return;
  3588.    }
  3589.    if ( srcMode != SM_I2O && !fileExists ( inName ) ) {
  3590.       fprintf ( stderr, "%s: Input file %s doesn't exist, skipping.\n",
  3591.                 progName, inName );
  3592.       return;
  3593.    }
  3594.    if ( srcMode != SM_I2O && !endsInBz2 ( inName )) {
  3595.       fprintf ( stderr,
  3596.                 "%s: Input file name %s doesn't end in `.bz2', skipping.\n",
  3597.                 progName, inName );
  3598.       return;
  3599.    }
  3600.    if ( srcMode != SM_I2O && notABogStandardFile ( inName )) {
  3601.       fprintf ( stderr, "%s: Input file %s is not a normal file, skipping.\n",
  3602.                 progName, inName );
  3603.       return;
  3604.    }
  3605.  
  3606.    switch ( srcMode ) {
  3607.  
  3608.       case SM_I2O:
  3609.          if ( isatty ( fileno ( stdin ) ) ) {
  3610.             fprintf ( stderr,
  3611.                       "%s: I won't read compressed data from a terminal.\n",
  3612.                       progName );
  3613.             fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
  3614.                               progName, progName );
  3615.             return;
  3616.          };
  3617.          inStr = stdin;
  3618.          break;
  3619.  
  3620.       case SM_F2O: case SM_F2F:
  3621.          inStr = fopen ( inName, "rb" );
  3622.          if ( inStr == NULL ) {
  3623.             fprintf ( stderr, "%s: Can't open input file %s, skipping.\n",
  3624.                       progName, inName );
  3625.             return;
  3626.          };
  3627.          break;
  3628.  
  3629.       default:
  3630.          panic ( "testf: bad srcMode" );
  3631.          break;
  3632.    }
  3633.  
  3634.    if (verbosity >= 1) {
  3635.       fprintf ( stderr, "  %s: ", inName );
  3636.       pad ( inName );
  3637.       fflush ( stderr );
  3638.    }
  3639.  
  3640.    /*--- Now the input handle is sane.  Do the Biz. ---*/
  3641.    allOK = testStream ( inStr );
  3642.  
  3643.    if (allOK && verbosity >= 1) fprintf ( stderr, "ok\n" );
  3644.    if (!allOK) testFailsExist = True;
  3645. }
  3646.  
  3647.  
  3648. /*---------------------------------------------*/
  3649. void license ( void )
  3650. {
  3651.    fprintf ( stderr,
  3652.  
  3653.     "bzip2, a block-sorting file compressor.  "
  3654.     "Version 0.1pl2, 29-Aug-97.\n"
  3655.     "   \n"
  3656.     "   Copyright (C) 1996, 1997 by Julian Seward.\n"
  3657.     "   \n"
  3658.     "   This program is free software; you can redistribute it and/or modify\n"
  3659.     "   it under the terms of the GNU General Public License as published by\n"
  3660.     "   the Free Software Foundation; either version 2 of the License, or\n"
  3661.     "   (at your option) any later version.\n"
  3662.     "   \n"
  3663.     "   This program is distributed in the hope that it will be useful,\n"
  3664.     "   but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  3665.     "   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
  3666.     "   GNU General Public License for more details.\n"
  3667.     "   \n"
  3668.     "   You should have received a copy of the GNU General Public License\n"
  3669.     "   along with this program; if not, write to the Free Software\n"
  3670.     "   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n"
  3671.     "   \n"
  3672.     "   The GNU General Public License is contained in the file LICENSE.\n"
  3673.     "   \n"
  3674.    );
  3675. }
  3676.  
  3677.  
  3678. /*---------------------------------------------*/
  3679. void usage ( Char *fullProgName )
  3680. {
  3681.    fprintf (
  3682.       stderr,
  3683.       "bzip2, a block-sorting file compressor.  "
  3684.       "Version 0.1pl2, 29-Aug-97.\n"
  3685.       "\n   usage: %s [flags and input files in any order]\n"
  3686.       "\n"
  3687.       "   -h --help           print this message\n"
  3688.       "   -d --decompress     force decompression\n"
  3689.       "   -f --compress       force compression\n"
  3690.       "   -t --test           test compressed file integrity\n"
  3691.       "   -c --stdout         output to standard out\n"
  3692.       "   -v --verbose        be verbose (a 2nd -v gives more)\n"
  3693.       "   -k --keep           keep (don't delete) input files\n"
  3694.       "   -L --license        display software version & license\n"
  3695.       "   -V --version        display software version & license\n"
  3696.       "   -s --small          use less memory (at most 2500k)\n"
  3697.       "   -1 .. -9            set block size to 100k .. 900k\n"
  3698.       "   --repetitive-fast   compress repetitive blocks faster\n"
  3699.       "   --repetitive-best   compress repetitive blocks better\n"
  3700.       "\n"
  3701.       "   If invoked as `bzip2', the default action is to compress.\n"
  3702.       "              as `bunzip2', the default action is to decompress.\n"
  3703.       "\n"
  3704.       "   If no file names are given, bzip2 compresses or decompresses\n"
  3705.       "   from standard input to standard output.  You can combine\n"
  3706.       "   flags, so `-v -4' means the same as -v4 or -4v, &c.\n"
  3707.       #if BZ_UNIX
  3708.       "\n"
  3709.       #endif
  3710.       ,
  3711.  
  3712.       fullProgName
  3713.    );
  3714. }
  3715.  
  3716.  
  3717. /*---------------------------------------------*/
  3718. /*--
  3719.   All the garbage from here to main() is purely to
  3720.   implement a linked list of command-line arguments,
  3721.   into which main() copies argv[1 .. argc-1].
  3722.  
  3723.   The purpose of this ridiculous exercise is to
  3724.   facilitate the expansion of wildcard characters
  3725.   * and ? in filenames for halfwitted OSs like
  3726.   MSDOS, Windows 95 and NT.
  3727.  
  3728.   The actual Dirty Work is done by the platform-specific
  3729.   macro APPEND_FILESPEC.
  3730. --*/
  3731.  
  3732. typedef
  3733.    struct zzzz {
  3734.       Char        *name;
  3735.       struct zzzz *link;
  3736.    }
  3737.    Cell;
  3738.  
  3739.  
  3740. /*---------------------------------------------*/
  3741. void *myMalloc ( Int32 n )
  3742. {
  3743.    void* p;
  3744.  
  3745.    p = malloc ( (size_t)n );
  3746.    if (p == NULL) {
  3747.       fprintf (
  3748.          stderr,
  3749.          "%s: `malloc' failed on request for %d bytes.\n",
  3750.          progName, n
  3751.       );
  3752.       exit ( 1 );
  3753.    }
  3754.    return p;
  3755. }
  3756.  
  3757.  
  3758. /*---------------------------------------------*/
  3759. Cell *mkCell ( void )
  3760. {
  3761.    Cell *c;
  3762.  
  3763.    c = (Cell*) myMalloc ( sizeof ( Cell ) );
  3764.    c->name = NULL;
  3765.    c->link = NULL;
  3766.    return c;
  3767. }
  3768.  
  3769.  
  3770. /*---------------------------------------------*/
  3771. Cell *snocString ( Cell *root, Char *name )
  3772. {
  3773.    if (root == NULL) {
  3774.       Cell *tmp = mkCell();
  3775.       tmp->name = (Char*) myMalloc ( 5 + strlen(name) );
  3776.       strcpy ( tmp->name, name );
  3777.       return tmp;
  3778.    } else {
  3779.       Cell *tmp = root;
  3780.       while (tmp->link != NULL) tmp = tmp->link;
  3781.       tmp->link = snocString ( tmp->link, name );
  3782.       return root;
  3783.    }
  3784. }
  3785.  
  3786.  
  3787.  
  3788. /*---------------------------------------------*/
  3789. #define ISFLAG(s) (strcmp(aa->name, (s))==0)
  3790.  
  3791.  
  3792. IntNative main ( IntNative argc, Char *argv[] )
  3793. {
  3794.    Int32  i, j;
  3795.    Char   *tmp;
  3796.    Cell   *argList;
  3797.    Cell   *aa;
  3798.  
  3799.  
  3800.    #if DEBUG
  3801.       fprintf ( stderr, "bzip2: *** compiled with debugging ON ***\n" );
  3802.    #endif
  3803.  
  3804.    /*-- Be really really really paranoid :-) --*/
  3805.    if (sizeof(Int32) != 4 || sizeof(UInt32) != 4  ||
  3806.        sizeof(Int16) != 2 || sizeof(UInt16) != 2  ||
  3807.        sizeof(Char)  != 1 || sizeof(UChar)  != 1) {
  3808.       fprintf ( stderr,
  3809.                 "bzip2: I'm not configured correctly for this platform!\n"
  3810.                 "\tI require Int32, Int16 and Char to have sizes\n"
  3811.                 "\tof 4, 2 and 1 bytes to run properly, and they don't.\n"
  3812.                 "\tProbably you can fix this by defining them correctly,\n"
  3813.                 "\tand recompiling.  Bye!\n" );
  3814.       exit(1);
  3815.    }
  3816.  
  3817.  
  3818.    /*-- Set up signal handlers --*/
  3819.    signal (SIGINT,  mySignalCatcher);
  3820.    signal (SIGTERM, mySignalCatcher);
  3821.    signal (SIGSEGV, mySIGSEGVorSIGBUScatcher);
  3822.    #if BZ_UNIX
  3823.    #ifndef BZ_AMIGA
  3824.    signal (SIGHUP,  mySignalCatcher);
  3825.    signal (SIGBUS,  mySIGSEGVorSIGBUScatcher);
  3826.    #endif
  3827.    #endif
  3828.  
  3829.  
  3830.    /*-- Initialise --*/
  3831.    outputHandleJustInCase  = NULL;
  3832.    ftab                    = NULL;
  3833.    ll4                     = NULL;
  3834.    ll16                    = NULL;
  3835.    ll8                     = NULL;
  3836.    tt                      = NULL;
  3837.    block                   = NULL;
  3838.    zptr                    = NULL;
  3839.    smallMode               = False;
  3840.    keepInputFiles          = False;
  3841.    verbosity               = 0;
  3842.    blockSize100k           = 9;
  3843.    testFailsExist          = False;
  3844.    bsStream                = NULL;
  3845.    numFileNames            = 0;
  3846.    numFilesProcessed       = 0;
  3847.    workFactor              = 30;
  3848.  
  3849.    strcpy ( inName,  "(none)" );
  3850.    strcpy ( outName, "(none)" );
  3851.  
  3852.    strcpy ( progNameReally, argv[0] );
  3853.    progName = &progNameReally[0];
  3854.    for (tmp = &progNameReally[0]; *tmp != '\0'; tmp++)
  3855.       if (*tmp == PATH_SEP) progName = tmp + 1;
  3856.  
  3857.  
  3858.    /*-- Expand filename wildcards in arg list --*/
  3859.    argList = NULL;
  3860.    for (i = 1; i <= argc-1; i++)
  3861.       APPEND_FILESPEC(argList, argv[i]);
  3862.  
  3863.  
  3864.    /*-- Find the length of the longest filename --*/
  3865.    longestFileName = 7;
  3866.    numFileNames    = 0;
  3867.    for (aa = argList; aa != NULL; aa = aa->link)
  3868.       if (aa->name[0] != '-') {
  3869.          numFileNames++;
  3870.          if (longestFileName < (Int32)strlen(aa->name) )
  3871.             longestFileName = (Int32)strlen(aa->name);
  3872.       }
  3873.  
  3874.  
  3875.    /*-- Determine what to do (compress/uncompress/test). --*/
  3876.    /*-- Note that subsequent flag handling may change this. --*/
  3877.    opMode = OM_Z;
  3878.  
  3879.    if ( (strcmp ( "bunzip2",     progName ) == 0) ||
  3880.         (strcmp ( "BUNZIP2",     progName ) == 0) ||
  3881.         (strcmp ( "bunzip2.exe", progName ) == 0) ||
  3882.         (strcmp ( "BUNZIP2.EXE", progName ) == 0) )
  3883.       opMode = OM_UNZ;
  3884.  
  3885.  
  3886.    /*-- Determine source modes; flag handling may change this too. --*/
  3887.    if (numFileNames == 0)
  3888.       srcMode = SM_I2O; else srcMode = SM_F2F;
  3889.  
  3890.  
  3891.    /*-- Look at the flags. --*/
  3892.    for (aa = argList; aa != NULL; aa = aa->link)
  3893.       if (aa->name[0] == '-' && aa->name[1] != '-')
  3894.          for (j = 1; aa->name[j] != '\0'; j++)
  3895.             switch (aa->name[j]) {
  3896.                case 'c': srcMode          = SM_F2O; break;
  3897.                case 'd': opMode           = OM_UNZ; break;
  3898.                case 'f': opMode           = OM_Z; break;
  3899.                case 't': opMode           = OM_TEST; break;
  3900.                case 'k': keepInputFiles   = True; break;
  3901.                case 's': smallMode        = True; break;
  3902.                case '1': blockSize100k    = 1; break;
  3903.                case '2': blockSize100k    = 2; break;
  3904.                case '3': blockSize100k    = 3; break;
  3905.                case '4': blockSize100k    = 4; break;
  3906.                case '5': blockSize100k    = 5; break;
  3907.                case '6': blockSize100k    = 6; break;
  3908.                case '7': blockSize100k    = 7; break;
  3909.                case '8': blockSize100k    = 8; break;
  3910.                case '9': blockSize100k    = 9; break;
  3911.                case 'V':
  3912.                case 'L': license();            break;
  3913.                case 'v': verbosity++; break;
  3914.                case 'h': usage ( progName );
  3915.                          exit ( 1 );
  3916.                          break;
  3917.                default:  fprintf ( stderr, "%s: Bad flag `%s'\n",
  3918.                                    progName, aa->name );
  3919.                          usage ( progName );
  3920.                          exit ( 1 );
  3921.                          break;
  3922.          }
  3923.  
  3924.    /*-- And again ... --*/
  3925.    for (aa = argList; aa != NULL; aa = aa->link) {
  3926.       if (ISFLAG("--stdout"))            srcMode          = SM_F2O;  else
  3927.       if (ISFLAG("--decompress"))        opMode           = OM_UNZ;  else
  3928.       if (ISFLAG("--compress"))          opMode           = OM_Z;    else
  3929.       if (ISFLAG("--test"))              opMode           = OM_TEST; else
  3930.       if (ISFLAG("--keep"))              keepInputFiles   = True;    else
  3931.       if (ISFLAG("--small"))             smallMode        = True;    else
  3932.       if (ISFLAG("--version"))           license();                  else
  3933.       if (ISFLAG("--license"))           license();                  else
  3934.       if (ISFLAG("--repetitive-fast"))   workFactor = 5;             else
  3935.       if (ISFLAG("--repetitive-best"))   workFactor = 150;           else
  3936.       if (ISFLAG("--verbose"))           verbosity++;                else
  3937.       if (ISFLAG("--help"))              { usage ( progName ); exit ( 1 ); }
  3938.          else
  3939.          if (strncmp ( aa->name, "--", 2) == 0) {
  3940.             fprintf ( stderr, "%s: Bad flag `%s'\n", progName, aa->name );
  3941.             usage ( progName );
  3942.             exit ( 1 );
  3943.          }
  3944.    }
  3945.  
  3946.    if (opMode == OM_Z && smallMode) blockSize100k = 2;
  3947.  
  3948.    if (opMode == OM_Z && srcMode == SM_F2O && numFileNames > 1) {
  3949.       fprintf ( stderr, "%s: I won't compress multiple files to stdout.\n",
  3950.                 progName );
  3951.       exit ( 1 );
  3952.    }
  3953.  
  3954.    if (srcMode == SM_F2O && numFileNames == 0) {
  3955.       fprintf ( stderr, "%s: -c expects at least one filename.\n",
  3956.                 progName );
  3957.       exit ( 1 );
  3958.    }
  3959.  
  3960.    if (opMode == OM_TEST && srcMode == SM_F2O) {
  3961.       fprintf ( stderr, "%s: -c and -t cannot be used together.\n",
  3962.                 progName );
  3963.       exit ( 1 );
  3964.    }
  3965.  
  3966.    if (opMode != OM_Z) blockSize100k = 0;
  3967.  
  3968.    if (opMode == OM_Z) {
  3969.       allocateCompressStructures();
  3970.       if (srcMode == SM_I2O)
  3971.          compress ( NULL );
  3972.          else
  3973.          for (aa = argList; aa != NULL; aa = aa->link)
  3974.             if (aa->name[0] != '-') {
  3975.                numFilesProcessed++;
  3976.                compress ( aa->name );
  3977.             }
  3978.    } else
  3979.    if (opMode == OM_UNZ) {
  3980.       if (srcMode == SM_I2O)
  3981.          uncompress ( NULL );
  3982.          else
  3983.          for (aa = argList; aa != NULL; aa = aa->link)
  3984.             if (aa->name[0] != '-') {
  3985.                numFilesProcessed++;
  3986.                uncompress ( aa->name );
  3987.             }
  3988.    } else {
  3989.       testFailsExist = False;
  3990.       if (srcMode == SM_I2O)
  3991.          testf ( NULL );
  3992.          else
  3993.          for (aa = argList; aa != NULL; aa = aa->link)
  3994.             if (aa->name[0] != '-') {
  3995.                numFilesProcessed++;
  3996.                testf ( aa->name );
  3997.             }
  3998.       if (testFailsExist) {
  3999.          fprintf ( stderr,
  4000.            "\n"
  4001.            "You can use the `bzip2recover' program to *attempt* to recover\n"
  4002.            "data from undamaged sections of corrupted files.\n\n"
  4003.          );
  4004.          exit(2);
  4005.       }
  4006.    }
  4007.    return 0;
  4008. }
  4009.  
  4010.  
  4011. /*-----------------------------------------------------------*/
  4012. /*--- end                                         bzip2.c ---*/
  4013. /*-----------------------------------------------------------*/
  4014.